RESTful Java client with Apache HttpClient
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 “GET” and “POST” request.
Note
The RESTful services from last “Jackson + JAX-RS” article will be reused.
The RESTful services from last “Jackson + JAX-RS” article will be reused.
1. Get 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>
2. GET Request
Review last REST service again.
@Path("/json/product") public class JSONService { @GET @Path("/get") @Produces("application/json") public Product getProductInJSON() { Product product = new Product(); product.setName("iPad 3"); product.setQty(999); return product; } //...
Apache HttpClient to send a “GET” request.
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; public class ApacheHttpClientGet { public static void main(String[] args) { try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet getRequest = new HttpGet( "http://localhost:8080/RESTfulExample/json/product/get"); getRequest.addHeader("accept", "application/json"); HttpResponse response = httpClient.execute(getRequest); if (response.getStatusLine().getStatusCode() != 200) { 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 (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
Output…
Output from Server .... {"qty":999,"name":"iPad 3"}
3. POST Request
Review last REST service also.
@Path("/json/product") public class JSONService { @POST @Path("/post") @Consumes("application/json") public Response createProductInJSON(Product product) { String result = "Product created : " + product; return Response.status(201).entity(result).build(); } //...
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/RESTfulExample/json/product/post"); StringEntity input = new StringEntity("{\"qty\":100,\"name\":\"iPad 4\"}"); 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(); } } }
Output…
Output from Server .... Product created : Product [name=iPad 4, qty=100]
Download Source Code
Download it – RESTful-Java-Client-ApacheHttpClient-Example.zip (9 KB)
References
Tags : client httpclient jax-rs restful

Have you ever considered about including a little bit more than just your articles?
I mean, what you say is fundamental and all. However think about
if you added some great graphics or videos to give your posts more, “pop”!
Your content is excellent but with pics and video clips, this website could undeniably
be one of the very best in its field. Fantastic blog!
i don’t get how to give Basic Authentication during multiple post requests from a standalone application using with Base64Encoder.
anyone solve my problem.
Please help me
Thanks with regards.
I WILL GET THIS EXCEPTION: anyone help me: ASHOK
————————- ****************
Exception in thread “main” java.lang.NoClassDefFoundError: org/apache/commons/codec/binary/Base64
at org.apache.http.impl.auth.BasicScheme.authenticate(BasicScheme.java:163)
at org.apache.http.impl.auth.BasicScheme.authenticate(BasicScheme.java:135)
at org.apache.http.client.protocol.RequestTargetAuthentication.process(RequestTargetAuthentication.java:99)
at org.apache.http.protocol.BasicHttpProcessor.process(BasicHttpProcessor.java:251)
at org.apache.http.protocol.HttpRequestExecutor.preProcess(HttpRequestExecutor.java:168)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:422)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:641)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:576)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:554)
at GetRe.main(GetRe.java:164)
MY CODE is HERE:
________________
public class PostRequest {
static Logger log = Logger.getLogger(GetRe.class);
public static HttpClient wrapClient(HttpClient base) {
try {
SSLContext ctx = SSLContext.getInstance(“TLS”);
X509TrustManager tm = new X509TrustManager() {
@SuppressWarnings(“unused”)
public void checkClientTrusted(X509Certificate[] xcs,
String string) throwsCertificateException{
}
@SuppressWarnings(“unused”)
public void checkServerTrusted(X509Certificate[] xcs,
String string) throwsCertificateException{
}
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] arg0, String arg1)
throws java.security.cert.CertificateException
{
// TODO Auto-generated method stub
}
@Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] arg0, String arg1)
throws java.security.cert.CertificateException {
// TODO Auto-generated method stub
}
};
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, 8443));
return new DefaultHttpClient(ccm, base.getParams());
} catch (Exception ex) {
return null;
}
}
// http://localhost:8080/RESTfulExample/json/product/post
public static void main(String[] args) {
Properties logProp = new Properties();
try {
String username = “”;
String password = “”;
logProp.load(new FileInputStream(“login.properties”));
if (logProp != null) {
username = logProp.getProperty(“username”);
password = logProp.getProperty(“password”);
}
if (username.equals(“”) && password.equals(“”)) {
log.error(“the username and password fields are empty”);
} else {
HttpClient httpClient = new DefaultHttpClient();
httpClient = wrapClient(httpClient);
DefaultHttpClient httpClient1 = (DefaultHttpClient) httpClient;
httpClient1.getCredentialsProvider().setCredentials(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT,
AuthScope.ANY_REALM, “basic”),
new UsernamePasswordCredentials(“mifos”, “password”));
JSONObject object = new JSONObject();
object.put(“serviceCode”, “ashok1″);
object.put(“serviceDescription”, “reddy2″);
object.put(“serviceType”, new Long(101));
System.out.println(“————” + object.toString());
StringEntity se = new StringEntity(object.toString());
HttpPost postRequest1 = new HttpPost(“https://localhost:8443″
+ “/mifosng-provider/api/v1/servicemasters”);
postRequest1.setHeader(“Content-Type”, “application/json”);
//postRequest1.setHeader(“tenantIdentifier”, “default”);
postRequest1.addHeader(“X-Mifos-Platform-TenantId”, “default”);
postRequest1.setEntity(se);
HttpResponse response1 = httpClient1.execute(postRequest1);
if (response1.getStatusLine().getStatusCode() != 200) {
log.error(“Failed : HTTP error code : ”
+ response1.getStatusLine().getStatusCode());
return;
}
BufferedReader br1 = new BufferedReader(new InputStreamReader(
(response1.getEntity().getContent())));
String output1;
System.out.println(“Output from Server …. \n”);
log.info(“Output from Server …. \n”);
while ((output1 = br1.readLine()) != null) {
log.info(output1);
}
httpClient1.getConnectionManager().shutdown();
httpClient.getConnectionManager().shutdown();
}
} catch (MalformedURLException e) {
log.error(“Exceptions happen!”, e);
} catch (IOException e) {
log.error(“Logging not enabled”, e);
log.error(“Exceptions happen!”, e);
} catch (Exception e) {
log.error(“Exceptions happen!”, e);
}
}
}
Hei man ,can you help me solve some questions? i am going to post a Base64 String to the rest server ,so how to make sure i can download this posted String .This is a real time process.should i use the database?Thank you very much!
Hello can any one tell how to excecute it in Eclipse Juno…
He given code but who has to tell how to execute?
Hey, man. That’s a great post.
I’d like to know if you have any experience combining REST, Apache HttpClient and OAuth.
The get was done pretty easily using signpost (for OAuth) and HttpURLConnection.
In singpost’s page it says ApacheComponents is the way for posts but I just can’t figure out how. Adapting your code here only led me to an error 500.
Best regards.
Hello,
you can take a look to glaze-http twitter example here: https://github.com/mfornos/glaze-http/tree/master/examples/src/main/java/glaze/examples/twitter
As a side note, glaze supports bean input and output mapping for restful clients out of the box.
The link to the project: http://mfornos.github.com/glaze-http/
hope it helps.
when i am using get method i am getting IllegalstateMonitor exception.Here i am passing the Url dyanamically.If i hard code the value of a url i am getting response from the server .
i cant understand why i am getting this error….?
How to resolve this error….?
plz send a mail how to resolve this problem …?
Thanks in advance.
Try not setting content-type in request. It should solve your issue :)
Hi thanks for your post, as it is very helpful in testing the REST ws.
Though I am easily able to check the get method using apache http client but unable to chek post method as it is throwing 415 – Unsupported Media Type for a json media type.
Please help me
Thanks with regards
Abdul Mannan