Can anyone explain me this code? - android

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).

Related

Alternative for UrlEncodedFormEntity for sending data via POST

When sending the POST request using UrlEncodedFormEntity which takes List as input parameter along with the key, my request gets converted in the form of [key={json}] .
But the request i want to send should be in the form of key={json} , i.e not as List.
So, is there any alternative for the given method when using POST?
notes: webservice is working fine , and since it is json ,i cannot use Soap .
i ve tested it using POSTman and webservices are WCF(if thats of any use..)
if any code is required , please mention it.
Thanks in advance.
Edit code:
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(URL);
List<NameValuePair> value=new ArrayList<NameValuePair>();
value.add(new BasicNameValuePair("data",string));
//here it passes as List and here is where i want an alternate method
// by which i can send parameter as JSONobject
UrlEncodedFormEntity entity=new UrlEncodedFormEntity(value);
request.setEntity(entity);
HttpResponse response = client.execute(request);
HttpEntity entity2 = response.getEntity();
if(entity2.getContentLength() != 0) {
Reader tapReader = new InputStreamReader(response.getEntity().getContent());
char[] buffer = new char[(int) response.getEntity().getContentLength()];
tapReader.read(buffer);
tapReader.close();
JSONObject tapJsonObj = new JSONObject(buffer);

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.

NameValuePair how to send blanks

I have a requirement to send some values to a service via HTTP POST. One of the parameters that gets sent must contain blanks. It is the "Key" nvp. But the service always returs a unsuccessful message, as soon as I add a value it work.
Now here is the catch, when the request is done to the same service via iphone device it works just fine when they send BLANKS, am I missing something in my request to allow blank values to be sent via NameVauePair?
Here is my NaveValuePair's
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("id","1"));
nameValuePairs.add(new BasicNameValuePair("uId",android_id));
nameValuePairs.add(new BasicNameValuePair("Key", " ")); // This value must be BLANKS
nameValuePairs.add(new BasicNameValuePair("Rate","0"));
nameValuePairs.add(new BasicNameValuePair("Notes", notes));
Here is my POST request
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(context.getResources()
.getString(R.string.url_event_rating));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8"));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String responseBody = EntityUtils.toString(response
.getEntity());
} catch (ClientProtocolException e) {
Log.d("ClientProtocolException", e.getMessage());
} catch (IOException e) {
Log.d("IOException", e.getMessage());
}
Try adding SP instead of a literal space character. This is the syntax given to you by BasicNameValuePair: http://developer.android.com/reference/org/apache/http/message/BasicNameValuePair.html (specifies a general overview of the class) and http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2.2 (specifies the tokens accepted).
Essentially, you want to insert SP instead of " ", according to what I've read on the topic.
Edit: According to the second link above: SP = <US-ASCII SP, space (32)>. Essentially, either place a character whose value is 32 (decimal) or 0x20 (hex). Or, change your encoding in UrlEncodedFormEntity(nameValuePairs, "utf-8") to "US-ASCII".
While we send a POST request there are field in HTTP Headers to be set, like the Content-Type field with value "application/x-www-form-urlencoded", which is default type. We should whatsoever encode the value field of request body before sending it. URLEncoder.encode(String s, String charsetName) functions encode a string with given charsetName i.e, 'utf-8'. The encoding used by default is based on a very early version of the general URI percent encoding rules.
one encoding example: a string like My Name is "Marshal" will be encoded as:
My%20Name%20is%20%22Marshal%22.
So, the safest way is to set (name, value) pair after encoding with this function. That is:
value = URLEncoder.encode(value, "utf-8");
nameValuePairs.add(new BasicNameValuePair(key, value));
Ok, there might be other ways to get this to work but the following code is what worked for me.
I got it to work using the following approach.
String blanks = " ";
nameValuePairs.add(new BasicNameValuePair("Key", blanks.replaceAll(" ", "%20")));
Hope this helps someone who has encountered the same problem.

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.

fail to send two parameters in http - post call

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.

Categories

Resources