Hi . In my previous posts , we talked about the basics of HttpClient ( Click here ) and how to use it safely in a multithreaded environment ( Click here ) . In this post we will learn how we can send POST request to a server using HttpClient .
Get Ready :
Download HttpClient dependencies and put them in the classpath of your application or if you are a maven user , add dependency in pom :
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3</version>
</dependency>
Lets take an example of form submission . HttpClient provides an entity class named
UrlEncodedFormEntity  to encode the form parameters that needs to be send as a part of POST request. List<NameValuePair> formData = new ArrayList<NameValuePair>();
formData.add(new BasicNameValuePair("param1", "value1"));
formData.add(new BasicNameValuePair("param2", "value2"));
// Creating UrlEncodedFormEntity that will use the URL encoding to encode form parameters 
// in a form like param1=value1¶m2=value2
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formData , Consts.UTF_8);
HttpPost httpPost= new HttpPost("Some URI");
httpPost.setEntity(entity);
Example :
This example below demonstrate the use of HttpClient to make a POST request .
package in.tutorialhub.httpclient;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
public class PostExample {
 public static void main(String[] args) throws Exception {
  // Creating an instance of HttpClient.
  CloseableHttpClient httpclient = HttpClients.createDefault();
  try {
   // Creating an instance of HttpPost.
   HttpPost httpost = new HttpPost("http://SomeRandomURI");
   // Adding all form parameters in a List of type NameValuePair
   List<NameValuePair> nvps = new ArrayList<NameValuePair>();
   nvps.add(new BasicNameValuePair("param1", "value1"));
   nvps.add(new BasicNameValuePair("param2", "value2"));
   /**
    * UrlEncodedFormEntity encodes form parameters and produce an
    * output like param1=value1¶m2=value2
    */
   httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
   // Executing the request.
   CloseableHttpResponse response = httpclient.execute(httpost);
   System.out.println("Response Status line :" + response.getStatusLine());
   try {
    // Do the needful with entity.
    HttpEntity entity = response.getEntity();
   } finally {
    // Closing the response
    response.close();
   }
  } finally {
   httpclient.close();
  }
 }
}

 
 

 
Hi Prakash,
ReplyDeleteNice tutorial. I am using it to access a website and logging in there, but with no success...
How do you get the html of the response? If i make response.toString()...i don't get the response page HTML ....
Regards,
This comment has been removed by the author.
DeleteHi majestade ,
DeleteYou can get the response from HttpEntity ( HttpEntity entity = response.getEntity(); )
So the code will be like :
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
See if this helps.
may be its not working
ReplyDeleteHi,
ReplyDeleteThanks for sharing this article the above article having a good content and valuable information. This helpful for java begineers.