Friday, 26 December 2014

How to use the HttpClient for HTTP POST Requests ?

Making an HTTP POST call is very similar to making an HTTP GET call.

HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost("your URL");
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("first","param value one"));
postParameters.add(new BasicNameValuePair("username","dave"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);

- We create an HttpClient and then instatntiate the HttpPost with the URL of the HTTP endpoint.
- Next we create a list of NameValuePair objects and populated it with several name/value parameters.
- We then create a UrlEncodedFormEntity instance,passing the list of NameValuePair objects to its
constructor.
- Finally,we called the setEntity() method of the POST request and then executed the request using the HttpClient instance.

* HTTP POST supports another request-body format known as a multipart POST.With this type of
POST ,you can send name / value parameters as before,along with arbitrary files.

* To do multipart POST calls,you need to get three additional Apache open source projects :
i)- Apache Commons IO.
ii)- Mime4j
iii)- HttpMime.

 


No comments:

Post a Comment