Ankit_Add

Tuesday, February 13, 2018

RESTful Java client with Apache HttpClient for Post

Apache HttpClient is a robust and complete solution Java library to perform HTTP operations, including RESTful service. In this tutorial, we show you how to create a RESTful Java client with Apache HttpClient, to perform a  “POST” request.



Post Apache HttpClient

Apache HttpClient is available in Maven central repository, just declares it in your Maven pom.xml file.
File : pom.xml
<dependency>
 <groupId>org.apache.httpcomponents</groupId>
 <artifactId>httpclient</artifactId>
 <version>4.1.1</version>
</dependency>
Apache HttpClient to send a “POST” request.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

public class ApacheHttpClientPost {

 public static void main(String[] args) {

   try {

  DefaultHttpClient httpClient = new DefaultHttpClient();
  HttpPost postRequest = new HttpPost(
   "http://localhost:8080-------------Restful API");

  StringEntity input = new StringEntity("{\"qty\":200,\"name\":\"item\"}");
  input.setContentType("application/json");
  postRequest.setEntity(input);

  HttpResponse response = httpClient.execute(postRequest);

  if (response.getStatusLine().getStatusCode() != 201) {
   throw new RuntimeException("Failed : HTTP error code : "
    + response.getStatusLine().getStatusCode());
  }

  BufferedReader br = new BufferedReader(
                        new InputStreamReader((response.getEntity().getContent())));

  String output;
  System.out.println("Output from Server .... \n");
  while ((output = br.readLine()) != null) {
   System.out.println(output);
  }

  httpClient.getConnectionManager().shutdown();

   } catch (MalformedURLException e) {

  e.printStackTrace();

   } catch (IOException e) {

  e.printStackTrace();

   }

 }

}


No comments:

Post a Comment