Wednesday, October 2, 2013

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