Monday, May 21, 2018

Usage of HttpClient

Add Bellow dependency.




<dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.1.1</version>
  </dependency>

--------------------------------------------------------------------------------------------------------------------------




public  String callAPI(String url) throws Exception {
  
  DefaultHttpClient httpClient = new DefaultHttpClient();
  String contentType = null;
  try {
   HttpGet get;
   HttpPost postRequest = new HttpPost(url);
   postRequest.addHeader("Content-Type", "application/x-www-form-urlencoded");
   postRequest.addHeader("Accept","application/pdf");
   HttpResponse postResponse = httpClient.execute(postRequest);
   
   int statusCode = postResponse.getStatusLine().getStatusCode();
   
   contentType = postResponse.getFirstHeader("Content-Type").toString();
   
            // Read the contents of an entity and return it as a String.
   //HttpEntity entity = postResponse.getEntity();
            //String content = EntityUtils.toString(entity);
   //int length = content.length();
   if(statusCode != 200){
    throw new RuntimeErrorException(null, "Failed with HTTP error code : " + statusCode);
   }
     
  } finally  {
   httpClient.getConnectionManager().shutdown();
  }
  return contentType;
 } 

No comments:

Post a Comment