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)
how to get user details using web service in java swing project
Try looking at http-rest-client
https://github.com/g00dnatur3/http-rest-client
Here is a simple example:
RestClient client = RestClient.builder().build();
String geocoderUrl = “http://maps.googleapis.com/maps/api/geocode/json”
Map params = Maps.newHashMap();
params.put(“address”, “beverly hills 90210?);
params.put(“sensor”, “false”);
JsonNode node = client.get(geocoderUrl, params, JsonNode.class);
Cheers!
wow! saved my time!
RestClient client = RestClient.builder().build();
was missing
Great example..thanks
thanks
Need help for Httpclient PUT
I have create a PUT HttpClient .
HttpPut httpPut
= new HttpPut(“url”);
setting header info in
httpPut.addHeader(“Content-Type”, “application/json”);
httpPut.addHeader(“SVC.ENVTESTTT” , “Value1”);
httpPut.addHeader(“SVC.ENVTESTTT” , “Value2”);
trying to pass converting json form to stringentity ..
httpPut.setEntity(“”) — but getting 400 bad response.
but NOT ABLE to pass raw body information
[
{
“feedId”: “37F1094E5A244664”,
“filter”: [
{
“filterName”: “FILTER”,
“filterValue”: [ “TRYYTTYT568”]
}
]
}
]
Hi,
Please can you give the example for POST the xls file through httpclient and how to read the xls file @client servlet without changing the checksum value.
Thanks
Suresh
Thanks Mkyong, your resource was helpfull
Hi can u give an example of PUT and DELETE also.
Thanks
private String sendDelete(String url, String projectId) throws IOException {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
//We just change HttpPost > HttpDelete
HttpDelete deleteRequest = new HttpDelete(String.format(url,projectId));
deleteRequest.addHeader(“accept”, “application/json”);
HttpResponse response = httpClient.execute(deleteRequest);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException(“Failed : HTTP error code : ”
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
System.out.println(“Output from Server …. n”);
StringBuffer result = new StringBuffer();
String output = “”;
while ((output = br.readLine()) != null) {
result.append(output);
}
httpClient.close();
return result.toString();
}
Hi MKYong,
What is the equivalent of @Consumes of JAX-RS in Spring MVC?
Regards
hi can u tell me how to sent object client side into service….
Hi,
could you tell me how i could pass the authentication parameters to a GET request in the REST java client code.
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.
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
Bad tutorial nothing explained wtf is “application/json”. If you mke tutorials you have to explain 🙁
Hi ,
How can i check for the headers in the URL and then check the Header Response data.I am getting 401 error all the time.In Postman i would be giving the URL with the Basic Authentication for the url to provide the Json Response.Can anyone please help me out in this regard.If their is anyother example where i can refer too.Can you please provide me the link if you get any
Thanks a lot
I don’t know how to use servlet.
I wanna know that i use index.jsp.
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!
Hi all,
I have created a simple post request, but it’s returning 422 status code:
public void createNewUser(){
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(
“http://test-www.nature.com/api/users”);
StringEntity input = new StringEntity(“{\”firstname\”:\”Deepak\”,\”lastname\”:\”Sharma\”,\”email\”:\”[email protected]\”,\”password\”:\”password\”}”);
input.setContentType(“application/json”);
postRequest.setEntity(input);
System.out.println(postRequest.getURI());
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();
}
}
———————–Error——-
[TestNG] Running:
/private/var/folders/lt/jxr2xw295d98wq_9xfgfmdjrg_7q0b/T/testng-eclipse-1291210530/testng-customsuite.xml
http://test-www.nature.com/api/users
FAILED: createNewUser
Creates a new user on Nature.com
java.lang.RuntimeException: Failed : HTTP error code : 422
at com.nature.foxtrot.tests.RestDemo.createNewUser(RestDemo.java:67)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
at org.testng.TestRunner.privateRun(TestRunner.java:767)
at org.testng.TestRunner.run(TestRunner.java:617)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
at org.testng.SuiteRunner.run(SuiteRunner.java:240)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
at org.testng.TestNG.run(TestNG.java:1057)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)
————————————
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);
}
}
}
Are you putting commons-codec-1.9.jar (or similar version) on your classpath?