Wednesday, November 13, 2013

Android Apache HTTP Client

Android Apache HTTP Client

In this post I want to describe how to build an HTTP client using Apache library. In one of my post I describe how we can use HttpUrlConnection to create a client. UsingApache library I want to explain how we can make POST requestdownload images and upload multipart binary data. Moreover I will describe how to exchange cookies. So the topics covered are:
  • POST request
  • download binary data
  • upload binary data
  • exchange cookie

Apache library is an external library shipped with Android SDK that simplifies the task of making HTTP request.

POST Request

As we know already POST and GET are the basic method that we can use to exchange data with a remote server.As example I will send to a remote server some data in text format (by now). So the first step is creating a DefaultHttpClient that is used a wrapper to send data.
1HttpClient client = new DefaultHttpClient();
Once we have our client we have to instantiate a class that handles POST request:
1HttpPost post = new HttpPost(url);
where url is the url we want to invoke. To send data we simply have to create a list of

NameValuePair a simple class that holds the name and the value of our parameters we want to send.

1List<NameValuePair> nvList = new ArrayList<NameValuePair>();
2BasicNameValuePair bnvp = new BasicNameValuePair("name", name);
3// We can add more
4nvList.add(bnvp);
In this case at line 2 we set the name of the parameter as name and we add the bnvp to the list as said before. Now we have build our list and set it inside our post request so that it can be sent:
1post.setEntity(new UrlEncodedFormEntity(nvList));
In this case we encode our parameters using Url encoding. The last step is executing the request through our DefaultHttpClient instance. As a result we obtain an HttpResponse that can be used to read the result of our request:
1HttpResponse resp = client.execute(post);
To read the response we can obtain an InputStream (line 1) and consume it reading data in this way:
1InputStream is  = resp.getEntity().getContent();           
2BufferedReader reader = new BufferedReader(new InputStreamReader(is));
3StringBuilder str = new StringBuilder();
4String line = null;
5while((line = reader.readLine()) != null){
6    str.append(line + "\n");
7}
8is.close();
9buffer.append(str.toString());
At the end we have a string that we can use to update our UI.
We have to remember that this operation can be time consuming so that we have to execute this request in an AsyncTask. For more information read the post ‘Android HTTP Client: GET, POST, Download, Upload, Multipart Request’.It is enough to say that all we have done by now should be inside the doInBackground method. Running the example we have:
Server side

No comments:

Post a Comment