In this article, we will see code for writing a REST client using HttpClient 3 api.
We will use the request/response is in JSON format.
serviceURL is the Rest service url that we need to connect to.
HttpClient 3 supports classes GetMethod and PostMethod through which we can do a Get or Post service call.
Here is the code for a POST service call:
PostMethod postMethod = new PostMethod(serviceURL); StringRequestEntity input = new StringRequestEntity( jsonRequest.toString(), "application/json", "UTF-8"); postMethod.setRequestEntity(input); HttpClient client = new HttpClient(); int statusCode = client.executeMethod(postMethod); if (statusCode != HttpStatus.SC_OK) { System.out.println("Service call failed: " + postMethod.getStatusLine()); } String responseBody = postMethod.getResponseBodyAsString(); JSONObject responseJSON = new JSONObject(responseBody);
For adding any header parameters, use the setRequestHeader method. For example, the below code adds header parameter param1 in the postMethod.
postMethod.setRequestHeader("param1", value1);
If you need to go through proxy for making the service call, then your proxy host and port need to be set in client host configuration.
String proxyHost = "yourproxyhostname"; int intProxyPort = "yourproxyhostname";
client.getHostConfiguration().setProxy(proxyHost, intProxyPort);
client.getHostConfiguration().setHost(proxyHost, 443, “https”);
© 2015, https:. All rights reserved. On republishing this post, you must provide link to original post
#