Pages

Thursday, June 5, 2014

XML over HTTP POST using Apache HTTPClient 4.x

Here is an Example on how to send XML data over HTTP POST using Apache HTTPClient 4.x

JARs required:
httpclient-4.3.3.jar
httpcore-4.3.2.jar
commons-logging-1.1.3.jar
commons-io-2.4.jar


package demo.pckg.httpclient;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.IOUtils;
import org.apache.http.Consts;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;

public class HTTPClientDemo {

 public static void main(String[] args) {

  String inputXML = "<data> <name>XYZ</name> <message>Hello XYZ...!!!</message> </data>";
  InputStream in ;
  StringEntity entity = new StringEntity(inputXML, ContentType.create(
    "text/xml", Consts.UTF_8));
  entity.setChunked(true);
  HttpPost httppost = new HttpPost(
    "http://localhost:8080/MyRestService/rest/UserService");

  httppost.setEntity(entity);

  HttpClient client = HttpClients.createDefault();

  try {
   HttpResponse response = client.execute(httppost);
   System.out.println(response.toString());
   in=response.getEntity().getContent();
   String body = IOUtils.toString(in);
   System.out.println(body);
  } catch (ClientProtocolException e) {
   System.out.println(e);
  } catch (IOException e) {
   System.out.println(e);
  }

 }
}