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.
1 | HttpClient client = new DefaultHttpClient(); |
Once we have our client we have to instantiate a class that handles POST request:
1 | 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.
1 | List<NameValuePair> nvList = new ArrayList<NameValuePair>(); |
2 | BasicNameValuePair bnvp = new BasicNameValuePair( "name" , name); |
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:
1 | 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:
1 | HttpResponse resp = client.execute(post); |
To read the response we can obtain an InputStream (line 1) and consume it reading data in this way:
1 | InputStream is = resp.getEntity().getContent(); |
2 | BufferedReader reader = new BufferedReader( new InputStreamReader(is)); |
3 | StringBuilder str = new StringBuilder(); |
5 | while ((line = reader.readLine()) != null ){ |
6 | str.append(line + "\n" ); |
9 | buffer.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