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.

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

References

  1. Jackson Official Website
  2. Apache HttpClient
  3. RESTful Java client with java.net.URL

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Vítor Amaral
Guest
Vítor Amaral

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.

mfornos
Guest
mfornos

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.

MyBean out = Get(uri). setAccept(APPLICATION_JSON).map(MyBean.class);

The link to the project: http://mfornos.github.com/glaze-http/

hope it helps.

realomok
Guest
realomok

I don’t know how to use servlet.
I wanna know that i use index.jsp.

Unmesh
Guest
Unmesh

Great example..thanks

kailas biradar
Guest
kailas biradar

how to get user details using web service in java swing project

jss
Guest
jss

thanks

Deepak
Guest
Deepak

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”]
}
]
}
]

Sureshraju
Guest
Sureshraju

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

g00dnatur3
Guest
g00dnatur3

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!

Mwesigye Johnbosco
Guest
Mwesigye Johnbosco

Thanks Mkyong, your resource was helpfull

Vikas Gupta
Guest
Vikas Gupta

Hi can u give an example of PUT and DELETE also.
Thanks

Ivan Trechyokas
Guest
Ivan Trechyokas
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(); }
trackback
JAX-RS TUTORIALS | BUYWORKSELL

[…] RESTful Java client with Apache HttpClient […]

Suresh
Guest
Suresh
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\”:\”suresh.kolli@mailinator.com\”,\”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]… Read more »
Abhisek
Guest
Abhisek

Hi MKYong,

What is the equivalent of @Consumes of JAX-RS in Spring MVC?

Regards

ram
Guest
ram

hi can u tell me how to sent object client side into service….

tina
Guest
tina

Hi,
could you tell me how i could pass the authentication parameters to a GET request in the REST java client code.

Ashok556
Guest
Ashok556

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.

Ashok556
Guest
Ashok556
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,… Read more »
Michael Munsey
Guest
Michael Munsey

Are you putting commons-codec-1.9.jar (or similar version) on your classpath?

Huigung
Guest
Huigung

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!

Girish
Guest
Girish

Hello can any one tell how to excecute it in Eclipse Juno…
He given code but who has to tell how to execute?

srikanth
Guest
srikanth

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.

sarang
Guest
sarang

Try not setting content-type in request. It should solve your issue :)

Abdul
Guest
Abdul

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

trackback
AMIS Technology blog » Create simple Java application to post JSON message to CometD Bayeux Channel using Apache HttpClient and Maven style NetBeans project

[…] describing the creation of an HTTP POST client using Apache HttpClient: http://www.mkyong.com/webservices/jax-rs/restful-java-client-with-apache-httpclient/ apache httpclient cometd http post httpclient Java […]

trackback
Create simple Java application to post JSON message to CometD Bayeux Channel using Apache HttpClient and Maven style NetBeans project « AMIS Technology blog

[…] describing the creation of an HTTP POST client using Apache HttpClient: http://www.mkyong.com/webservices/jax-rs/restful-java-client-with-apache-httpclient/ Tags: apache httpclient, cometd, http post, httpclient, Java, json Share this […]