Friday, December 20, 2013

RESTful Java Client for Apache HttpClient

Apache HttpClient is a robust and complete solution Java library to perform HTTP operations, including RESTful service. This blog post shows how to create a RESTful Java client with Apache HttpClient, to perform a “GET” and “POST” request.

Apache HttpClient is available in Maven central repository, just declares it in your Maven pom.xml file.

1
2
3
4
5
<dependency>
 <groupId>org.apache.httpcomponents</groupId>
 <artifactId>httpclient</artifactId>
 <version>4.1.1</version>
</dependency>

Following is the way to implement GET request.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public HttpResponse doGet(DefaultHttpClient httpClient, String resourcePath, String userName, String passWord) {
 try {
     HttpGet getRequest = new HttpGet(resourcePath);
     getRequest.addHeader("Content-Type", "application/json");

     String userPass = userName + ":" + passWord;
     String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userPass.getBytes("UTF-8"));
     getRequest.addHeader("Authorization", basicAuth);

     httpClient = (DefaultHttpClient) WebClientWrapper.wrapClient(httpClient);

     HttpParams params = httpClient.getParams();
     HttpConnectionParams.setConnectionTimeout(params, 300000);
     HttpConnectionParams.setSoTimeout(params, 300000);

     HttpResponse response = httpClient.execute(getRequest);

     return response;
 } catch (ClientProtocolException e) {
     e.printStackTrace();
     return null;
 } catch (IOException e) {
     e.printStackTrace();
     return null;
 }
}

Following is the way to implement POST request.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public HttpResponse doPost(DefaultHttpClient httpClient, String resourcePath, String jsonParamString, String userName,
                       String passWord) throws Exception{
 try {
     HttpPost postRequest = new HttpPost(resourcePath);

     StringEntity input = new StringEntity(jsonParamString);
     input.setContentType("application/json");
     postRequest.setEntity(input);

     String userPass = userName + ":" + passWord;
     String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userPass.getBytes("UTF-8"));
     postRequest.addHeader("Authorization", basicAuth);

     httpClient = (DefaultHttpClient) WebClientWrapper.wrapClient(httpClient);

     HttpParams params = httpClient.getParams();
     HttpConnectionParams.setConnectionTimeout(params, 300000);
     HttpConnectionParams.setSoTimeout(params, 300000);

     HttpResponse response = httpClient.execute(postRequest);

     return response;
 } catch (ClientProtocolException e) {
     throw new ClientProtocolException();
 } catch (ConnectException e) {
     throw new ConnectException();
 }
 catch (IOException e) {
     e.printStackTrace();
     return null;
 }
}

You can used WebClientWrapper class to ignore the certificate. You can find it from following.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;

public class WebClientWrapper {

    public static HttpClient wrapClient(HttpClient base) {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] xcs,
                                               String string) throws CertificateException {
                }

                public void checkServerTrusted(X509Certificate[] xcs,
                                               String string) throws CertificateException {
                }

                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            ctx.init(null, new TrustManager[] { tm }, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx);
            ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            ClientConnectionManager ccm = base.getConnectionManager();
            SchemeRegistry sr = ccm.getSchemeRegistry();
            sr.register(new Scheme("https", ssf, 443));
            return new DefaultHttpClient(ccm, base.getParams());
        } catch (Exception ex) {
            return null;
        }
    }
}


Java Code Geeks

1 comment:

  1. I have read your blog its very attractive and impressive. I like it your blog.

    Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

    Java Online Training Java Online Training Core Java 8 Training in Chennai Core java 8 online training JavaEE Training in Chennai Java EE Training in Chennai

    ReplyDelete