Tuesday, October 8, 2013

Android HTTP Client: GET, POST, Download, Upload, Multipart Request

Often Android apps have to exchange information with a remote server. The easiest way is to use the HTTP protocol as base to transfer information. There are several scenarios where the HTTP protocol is very useful like downloading an image from a remote server or uploading some binary data to the server. Android app performs GET or POST request to send data. In this post, we want to analyze how to use HttpURLConnection to communicate with a remote server. We will cover three main topics:
  • GET and POST requests
  • Download data from the server
  • Upload data to the server using MultipartRequest
As a server we will use three simple Servlet running inside Tomcat 7.0. We won’t cover how to create a Servlet using API 3.0 but the source code will be available soon.

GET and POST requests

GET and POST requests are the base blocks in HTTP protocol. To make this kind of requests we need first to open a connection toward the remove server:
1HttpURLConnection con = (HttpURLConnection) ( new URL(url)).openConnection();
2con.setRequestMethod("POST");
3con.setDoInput(true);
4con.setDoOutput(true);
5con.connect();
In the first line we get the HttpURLConnection, while in the line 2 we set the method and at the end we connect to the server.
Once we have opened the connection we can write on it using the OutputStream.
1con.getOutputStream().write( ("name=" + name).getBytes());
As we already know parameters are written using key value pair.
The last step is reading the response, using the InputStream:
1InputStream is = con.getInputStream();
2byte[] b = new byte[1024];
3while ( is.read(b) != -1)
4  buffer.append(new String(b));
5con.disconnect();
Everything is very simple by now, but we have to remember one thing: making an HTTP connection is a time consuming operation that could require long time sometime so we can’t run it in the main thread otherwise we could get a ANR problem. To solve it we can use an AsyncTask.
01private class SendHttpRequestTask extends AsyncTask<String, Void, String>{
02 
03  @Override
04  protected String doInBackground(String... params) {
05   String url = params[0];
06   String name = params[1];
07   String data = sendHttpRequest(url, name);
08   return data;
09  }
10 
11  @Override
12  protected void onPostExecute(String result) {
13   edtResp.setText(result);
14   item.setActionView(null);  
15  }
16}
Running the app we get:
android_httpclient_post_get_1android_httpclient_post_get_2
As we can see we post a name to the server and it responds with the classic ‘Hello….’. On the server side we can check that the server received correctly our post parameter:

No comments:

Post a Comment