Android Apache HTTP Client: Post, Download, Upload multipart

In this post I want to describe how to build an Android Apache HTTP client . In one of my post I describe how we can use HttpUrlConnection to create a client. Using Apache HTTP library I want to explain how we can send POST request, download images and upload multipart binary data. Moreover I will describe how to exchange cookies.

In Android 6.0 Marshmallow the Apache HTTP client has been removed. So if you are planning to implement app that supports Android 6.0 consider to use Android Http client.

If you still want to use Apache client you have to add these lines to build.gradle (compile-time):

android {
useLibrary 'org.apache.http.legacy'
}

Android Apache HTTP: 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.

HttpClient client = new DefaultHttpClient();

Once we have our client we have to instantiate a class that handles POST request:

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

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:

post.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:

HttpResponse resp = client.execute(post);

To read the response we can obtain an InputStream (line 1) and consume it reading data in this way:

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:

At line 17 we read the response length so that we can create a byte array with the same size (see line 21), then at line 19 we create a buffered input stream to read the response stream. Then we simply read the response filling the data byte array. As result we have:

Upload binary data

This is one of most interesting aspect. To handle this operation using android apache client, we need to add an external library to simplify the task. This is a drawback of using android apache http client respect to the android native api. On the other side as we saw android native api doesn’t handle multipart request so we have to do everything from zero. Using this library we can simplify the process but we have as a consequence a bigger apk at the end. The library is open source and it is called httpmime-xxx.jar. You can download it here. Remember to add it to your project and has to be exported (see Order and Export in Eclipse). As example we create a multipart request containing some text data and an image. So we start creating always our DefaultHttpClient and HttpPost:

and then add the single parts: two are text data and one is the binary data (the image we want to upload):

multiPart.addPart("param1", new StringBody(param1));
multiPart.addPart("param2", new StringBody(param2));
multiPart.addPart("file", new ByteArrayBody(baos.toByteArray(), "logo.png"));

Notice at line 3 we create a part using a ByteArrayBody to contain the binary data. Then we fill the post content with the data we created:

post.setEntity(multiPart);

and then we simply send (or post) it to the server:

client.execute(post);

Running the app we have:

Server side

Exchange Cookie

One interesting aspect in HTTP protocol is the cookie management. As we know HTTP is a stateless protocol so using cookies we can persist some information across HTTP requests. As example we can suppose to make two HTTP request: one where we invoke a URL and the server returns a cookie containing some information and another one where we send back to the server the cookie.

At line 1 we simply get the cookie store where the cookies are stored. At line 3 we retrieves the cookies list. In the second post request we have to maintain the cookie we retrieved in the first request so we have:

About The Author

I'm an electronic engineer with over 15 years of
experience in computer programming. I'm the author of the book "Android things projects". I'm a MVB at DZone and DZone Guide Author. I have contributed to the IoT guide. I'm the technical reviewer of the book Internet of Things with Arduino Blueprints(published by PacktPub). I love creating IoT projects using Arduino, Raspberry Pi,
Android, and other platforms. I am interested in the convergence
between IoT and the mobile applications. I'm SCEA, SCWCD, and SCJP
certified.
Follow on: Twitter | Linkedin

Eliax1996

Nice 🙂

Fred .

Google now discourages the use of DefaultHttpClient() and instead recommends HttpURLConnection.

DefaultHttpClientDefaultHttpClientDefaultHttpClient

survivingwithandroid

Yes but it is always an option

Fred .

I looked into HttpURLConnection to rewrite my old DefaultHttpClient but damn HttpURLConnection is an ugly API!

Sign up for our Newsletter

Enter your email and stay on top of things,

Get SwA updates delivered to your inbox. Article, tips, source code

×

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.