fail to send two parameters in http - post call - android

I trying to send two parameters to some server.
the server is responding to http-post call and the two parameters are
Int
Some Enum ( that i sending as string )
I want to send the parameters as json:
StringEntity t = new StringEntity("{ \"intValParam\":-100 , \"enumParam\":\"enumValueAsString\" }" , "UTF-8");
httppost.setEntity(t);
httppost.setHeader("content-type", "application/json");
The response that i get is 400 ( bad request )
** There is one more method that i can call that need to have one parameter ... only the int - and this method is working good - so this is not problem from the bad connection or something like that.

You should not try to add your parameters like that. Either use the method setParams from httpPost or use NameValuePair entities and encode them in your request, like that :
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("userid", "12312"));
nameValuePairs.add(new BasicNameValuePair("sessionid", "234"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
code taken here.

Related

json object post to php script in android app

I tried this android code for send json objects to my website
HttpPost httppost = new HttpPost(url);
JSONObject j = new JSONObject();
j.put("name","name ");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
String format = s.format(new Date());
nameValuePairs.add(new BasicNameValuePair("msg",j.toString() ));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
And this php code
<?php
$msg=$_POST["msg"];
$filename="androidmessages.html";
file_put_contents($filename,$msg."<br />",FILE_APPEND);
$androidmessages=file_get_contents($filename);
echo $androidmessages;
?>
It will show me {"name":"name "}
but if i use
httppost.setHeader( "Content-Type", "application/json" );
it will show nothing.I have no before experince about json object post but i think something went wrong.I want to send some user information to my website and display it in web page can you please tell me what i need to change to overcome this problem
Thank you
Finally i got the answer
$msg=json_decode(file_get_contents('php://input'), true);
$filename="androidmessages_json.html";
file_put_contents($filename,$msg['name']."<br />",FILE_APPEND);
$androidmessages=file_get_contents($filename);
echo $androidmessages;
It depends how you want to pass the data to your PHP-script.
If you want to get the JSON as a string in one variable (and maybe others in addition), then you should not use the content-type "application/json". If you want to only post the JSON without any variable, you can do the following instead:
HttpPost httppost = new HttpPost(url);
JSONObject j = new JSONObject();
j.put("name","name ");
httppost.setEntity(new StringEntity(j.toString());
httpclient.execute(httppost);
As you can imagine from the code you do not have the JSON in one POST-var only but in total.

Android HTTP GET parameters

I'm using the apache http library and need to know how to add a parameter to an HTTP GET request. I've looked over How to add parameters to a HTTP GET request in Android? but the accepted answer for that adds parameters to an HTTP POST. This is my code so far but it is not working.
HttpGet get = new HttpGet("https://server.com/stuff");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("count", "5"));
HttpParams p = get.getParams();
p.setParameter("length", "5");
get.setParams(p);
String url = "https://server.com/stuff"
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("count", "5"));
HttpClient httpClient = new DefaultHttpClient();
String paramsString = URLEncodedUtils.format(nameValuePairs, "UTF-8");
HttpGet httpGet = new HttpGet(url + "?" + paramsString);
HttpResponse response = httpClient.execute(httpGet);
EDIT: Since Android SDK v22, the type NameValuePair is deprecated. I recommend using Volley, an HTTP library that makes networking for Android apps easier and most importantly, faster.
unlike POST, GET sends the parameters under the url like this:
http://myurl.com?variable1=value&variable2=value2
Where: the parameters area start from the question mark and on so the variable1 is the first param and it has "value" value...
See here for more informations.
So what you need to do is just build an url that contains also these parameters according to server needs.
EDIT:
In your case :
HttpGet get = new HttpGet("https://server.com/stuff?count=5&length=5");
...
Where: count=5 and length=5 are the parameters and the "?" mark is the beginning of the parameters definition...
I hope that helps.

HTTPPOST to aspx file

I want to post to this url
http://abc.com/Registration.aspx?MailID=PickUp&UserName=as&PickUpTime=19191919&Notes=bla&DeviceId=0000
HttpPost httppost = new HttpPost("http://abc.com/Davis/Registration.aspx");
httppost.setHeader("MailID","MailID=PickUp");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
//nameValuePairs.add(new BasicNameValuePair("MailID","PickUp"));
nameValuePairs.add(new BasicNameValuePair("UserName","as"));
nameValuePairs.add(new BasicNameValuePair("PickUpTime",date));
nameValuePairs.add(new BasicNameValuePair("Notes",note));
nameValuePairs.add(new BasicNameValuePair("DeviceId",deviceID));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
Also how can I know what url I am passing . How can I log it ?
Are you sure MailID should be in the header? From the wording of the question, it looks as if all values are in the query string (in the URL past the ? mark). But then why would you need POST for that; a GET would be sufficient.
And passing data, like MailID, in headers is almost unheard of. Querystring and POST form, those are the most popular places.
So first figure out the interface of the server page. Does it expect GET or POST (or either)? Then place the fields into the right place - either into the URL (by string concatenation), or into the entity.
Oh, and the URL you're passing is http://abc.com/Davis/Registration.aspx. Neither setHeader() nor setEntity() modifies the URL per se.

BasicNameValuePair not working with # (at symbol) in value - Trying to create an HTTP POST request in Android

I am trying to create an HTTP POST request in android where I pass "username" and "password" as POST variables.
I have code that works under most circumstances. However when the password contains the "#" symbol it no longer works.
Here is my code
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpClient httpClient = new DefaultHttpClient(params);
HttpPost post = new HttpPost(url);
List<NameValuePair> postData = new ArrayList<NameValuePair>();
postData.add(new BasicNameValuePair("username", "the_username"));
postData.add(new BasicNameValuePair("password", "the_password"));
post.setEntity(new UrlEncodedFormEntity(postData, HTTP.UTF_8));
HttpResponse response = httpClient.execute(post);
If "the_password" contains an #, such as "the_password#" then I'm not sure what the POST sends over the wire, but I get an error from the server.
The documentation indicates that certain special characters have to be escaped, but I'm not what API call to use to do that - and I have had no luck trying to manually escape the characters in my hard coded string.
Further more if I replace the following line:
post.setEntity(new UrlEncodedFormEntity(postData, HTTP.UTF_8));
with
post.setEntity(new StringEntity("username=the_username&password=the_password#", HTTP.UTF_8));
Then everything works - but this isn't a great solution because username and password are user entered and I'm unsure as to how that will work if they pass in a string with ampersand (&) or equals(=) in it
Any thoughts??
Are you sure your server correctly handles URL-escaped parameters?
If I run this:
List<NameValuePair> postData = new ArrayList<NameValuePair>();
postData.add(new BasicNameValuePair("username", "the_username"));
postData.add(new BasicNameValuePair("password", "the_password#"));
String urlencoform = EntityUtils.toString(new UrlEncodedFormEntity(postData, HTTP.UTF_8));
String directstring = EntityUtils.toString(new StringEntity("username=the_username&password=the_password#", HTTP.UTF_8));
I get:
urlencoform = "username=the_username&password=the_password%40"
directstring = "username=the_username&password=the_password#"
So this means it "works" with your server if you're sending unencoded parameters. This can't be good.
Any change to check what the server is receiving and how it does/does not handle it?

Can anyone explain me this code?

import org.apache.http.message.BasicNameValuePair;
private String getServerData(String returnString) {
InputStream is = null;
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year","1970"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(KEY_121);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
}
My Questions...
What does BasicNameValuePair class does?
What does this piece of line do
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
What does is = entity.getContent(); do? and can i pass more than one value in BasicNameValuePair class. Can i entirely pass a VO instead of this.
Like the below ...
nameValuePairs.add(new BasicNameValuePair("year","1970","sas","saassa","sas","asas"));
BasicNameValuePair is an object, specifically a container to holds data and keys.
For example if you have this data:
Name: Bob
Family name: Smith
Date of birth: 10/03/1977
then you would store this data as:
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name","bob"));
nameValuePairs.add(new BasicNameValuePair("family name","Smith"));
....
As you see you choose a key ("name") and data to be stored as linked to the key ("bob"). It's a type of data structure used to speed up and make easier to store this kind of informations.
On the other end you need a tool to use this data:
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
this code can be divided in 4 parts:
httppost.setEntity: Is a method that take an url as argument, and tries to retrieve data (HTML or what is stored on that page) from that url, using the HTTP Post method.
new UrlEncodedFormEntity: Is a method that trasform key-data value pair in something intelligible by an http server.
it use the convention: &key=input, which one of the most used, but remember that there more ways to do it.
nameValuePair: is the data you stored before. In this case it has key the possible input forms in the html, identified by the "input name=" tag. As data it has the value that you want to give to the forms.
is = entity.getContent();: HttpEntity is an abstraction to help you handle the possible result. If the web site is unreachable or the connection is down, HttpEntity will inform you. getContent() is the method you use the retrieve the body of the Http result, i.e.: the html that the webserver sent you back, as a inputstream. If the request wasn't succesfull it will give you a null value.
BasicNameValuePair accept only couplets, so you'll have to cast it multiple times and everytime add it to the arraylist.
You can't cast it to more than two values, as they would be meaningless for the (key, value) representation of data.
Hope it helped.
In the end you're doing a http POST request with the field "year" having the value "1970".
Just like a webform posting that year would.
A bit extra:
The BasicNameValuePair looks quite aptly named: Its a very simple (basic) group of two things (pair) that serve as a formfield (name) and its contents (value).
The httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); adds that combination of year and 1970 to the HttpPost object, but with encoding (so there are no 'illegal' things in there).

Categories

Resources