Tuesday, March 8, 2016

Calling HTTPS REST API from JAVA using HTTPClient and Jersey

Apache HTTP Client
==================
import java.io.File;

import java.net.URI;

import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;


public class JavaHttpsRestCall {
  public static void main(String[] args) throws Exception {
    //Optional if the certificate is in the right truststore
    String keystorePath = "lib/DevDemoTrust.jks";
    File keyStoreFile = new File(keystorePath);
    System.setProperty("javax.net.ssl.trustStore",    keyStoreFile.getAbsolutePath());

    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials =   new UsernamePasswordCredentials("khaleel", "pwd123");
 
    CloseableHttpClient httpclient = HttpClients.createDefault();
 
    try {
          URI uri =  new URIBuilder().setScheme("https").setHost("devlattice.bigmachines.com")
              .setPath("/rest/v1/commerceDocumentsOraclecpqoTransaction")
              .setParameter("q","{'lastPricedDate_t': {$gt: '2015-10-27T12:30:00'}}")
              .setParameter("expand","transactionLine")
              .setParameter("limit","5")
              .setParameter("offset","0")
              .setParameter("totalResults","true").build();
     
        HttpGet httpget = new HttpGet(uri);
          httpget.addHeader(new BasicScheme().authenticate(credentials, httpget, null));
          //httpget.addHeader("accept", "application/json");
          //httpget.addHeader("Content-Type", "application/json");
     
      System.out.println("Executing request " + httpget.getRequestLine());
      CloseableHttpResponse response = httpclient.execute(httpget);
      try {
        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        System.out.println(EntityUtils.toString(response.getEntity()));
        System.out.println("----------------------------------------");
      } finally {
        response.close();
      }
    } finally {
      httpclient.close();
    }

  }
}

Apache Jersey
=================
import sun.misc.BASE64Encoder;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import org.apache.http.client.utils.URIBuilder;

import java.io.File;

import java.net.URI;

import org.apache.http.client.utils.URIBuilder;

public class JerseyClient {

  public static void main(String[] a) throws Exception {

    String keystorePath = "lib/DevDemoTrust.jks";
    File keyStoreFile = new File(keystorePath);
    System.setProperty("javax.net.ssl.trustStore",
                       keyStoreFile.getAbsolutePath());
   
    String url =     "https://devkk.bigmachines.com/rest/v1/commerceDocumentsOraclecpqoTransaction?expand=transactionLine&q=%7B+%27lastPricedDate_t%27%3A+%7B%24gt%3A+%272015-10-27T12%3A30%3A00%27%7D%7D&limit=10&offset=0&totalResults=true";

    URI uri =  new URIBuilder().setScheme("https").setHost("devlattice.bigmachines.com")
      .setPath("/rest/v1/commerceDocumentsOraclecpqoTransaction")
      .setParameter("q","{'lastPricedDate_t': {$gt: '2015-10-27T12:30:00'}}")
      .setParameter("expand","transactionLine")
      .setParameter("limit","100")
      .setParameter("offset","0")
      .setParameter("totalResults","true").build();

    String name = "kshaik";
    String password = "pwd123";
    String authString = name + ":" + password;
    String authStringEnc = new BASE64Encoder().encode(authString.getBytes());
    System.out.println("Base64 encoded auth string: " + authStringEnc);
    Client restClient = Client.create();
    WebResource webResource = restClient.resource(url);
    ClientResponse resp =
      webResource.accept("application/json").header("Authorization",
                                                    "Basic " + authStringEnc).get(ClientResponse.class);
    if (resp.getStatus() != 200) {
      System.err.println("Unable to connect to the server");
    }
    String output = resp.getEntity(String.class);
    System.out.println("response: " + output);
  }
}


No comments: