Skip to content Skip to sidebar Skip to footer

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 t

Solution 1:

BasicNameValuePair is an object, specifically a container to holds data and keys.

For example if you have this data:

Name:BobFamily name:SmithDate 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(newUrlEncodedFormEntity(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.

Solution 2:

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

Post a Comment for "Can Anyone Explain Me This Code?"