tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 
 Tools and Libs > Commons Http Client > HTTP POST Request with String Entity Body

HTTP POST Request with String Entity Body 

Commons Http Client is a HTTP agent implementation in java supporting client-side authentication, HTTP state management and HTTP connection management. This requires the libraries httpclient-4.1.2.jar, httpcore-4.1.2.jar, httpmime-4.1.2.jar, httpclient-cache-4.1.2.jar, commons-codec.jar and commons-logging-1.1.1.jar to be in classpath. The following example shows how to make Http Post request with String Entity body.

File Name  :  
com/bethecoder/tutorials/commons_httpclient/SimplePostRequestTest2.java 
Author  :  Sudhakar KV
Email  :  kvenkatasudhakar@gmail.com
   
package com.bethecoder.tutorials.commons_httpclient;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

public class SimplePostRequestTest2 {

  /**
   @param args
   */
  public static void main(String[] args) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://localhost:8080/HTTP_TEST_APP/postreq.jsp");
    System.out.println("Requesting : " + httppost.getURI());

    try {
      StringEntity entity = new StringEntity(
          "<DocSearch><searchString>*.pdf</searchString>" +
          "<userName>Sudhakar KV</userName></DocSearch>"
          "text/xml""ISO-8859-1");

      httppost.addHeader("Accept" "text/xml");
      httppost.setEntity(entity);

      ResponseHandler<String> responseHandler = new BasicResponseHandler();
      String responseBody = httpclient.execute(httppost, responseHandler);

      System.out.println("responseBody : " + responseBody);

    catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    catch (ClientProtocolException e) {
      e.printStackTrace();
    catch (IOException e) {
      e.printStackTrace();
    finally {
      httpclient.getConnectionManager().shutdown();
    }
  }

}
   

A simple Web Application which prints the request headers, parameters and body through JSP.

File Name  :  
/HTTP_TEST_APP/WebContent/postreq.jsp 

It gives the following output,
File Name  :  OUTPUT


                    Print

   



Books Recommendation

 
 
bl  br