Apache HttpClient GET and POST examples

We have learned about building RESTful webservices already. Now learn to build a JAX-RS REST client for consuming the webservices using HttpClient RESTful Client.

I will be reusing the code written for jaxrs xml example.

The HTTP GET and POST REST APIs which I will be accessing are as defined.

@GET
@Path("/users/{id}")
public User getUserById (@PathParam("id") Integer id) 
{
	User user = new User();
	user.setId(id);
	user.setFirstName("demo");
	user.setLastName("user");
	return user;
}

@POST
@Path("/users")
public User addUser() 
{
   //Some code
}

To build a RESTful client using apache httpclient, follow below instruction.

1. Apache HttpClient maven dependency

<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.1.1</version>
</dependency>

2. Apache HttpClient GET API Example

Java program for how to send json data using http get request.

public static void demoGetRESTAPI() throws Exception 
{
	DefaultHttpClient httpClient = new DefaultHttpClient();
	try
	{
		//Define a HttpGet request; You can choose between HttpPost, HttpDelete or HttpPut also.
		//Choice depends on type of method you will be invoking.
		HttpGet getRequest = new HttpGet("http://localhost:8080/RESTfulDemoApplication/user-management/users/10");
		
		//Set the API media type in http accept header
		getRequest.addHeader("accept", "application/xml");
		 
		//Send the request; It will immediately return the response in HttpResponse object
		HttpResponse response = httpClient.execute(getRequest);
		
		//verify the valid error code first
		int statusCode = response.getStatusLine().getStatusCode();
		if (statusCode != 200) 
		{
			throw new RuntimeException("Failed with HTTP error code : " + statusCode);
		}
		
		//Now pull back the response object
		HttpEntity httpEntity = response.getEntity();
		String apiOutput = EntityUtils.toString(httpEntity);
		
		//Lets see what we got from API
		System.out.println(apiOutput); //<user id="10"><firstName>demo</firstName><lastName>user</lastName></user>
		
		//In realtime programming, you will need to convert this http response to some java object to re-use it.
		//Lets see how to jaxb unmarshal the api response content
		JAXBContext jaxbContext = JAXBContext.newInstance(User.class);
		Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
		User user = (User) jaxbUnmarshaller.unmarshal(new StringReader(apiOutput));
		
		//Verify the populated object
		System.out.println(user.getId());
		System.out.println(user.getFirstName());
		System.out.println(user.getLastName());
	}
	finally
	{
		//Important: Close the connect
		httpClient.getConnectionManager().shutdown();
	}
}

3. Apache HttpClient POST API example with json body

Java program for how to send json data to server using http post request.

public static void demoPostRESTAPI() throws Exception 
{
	DefaultHttpClient httpClient = new DefaultHttpClient();
	
	User user = new User();
	user.setId(100);
	user.setFirstName("Lokesh");
	user.setLastName("Gupta");
	
	StringWriter writer = new StringWriter();
	JAXBContext jaxbContext = JAXBContext.newInstance(User.class);
	Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
	jaxbMarshaller.marshal(user, writer);
	
	try
	{
		//Define a postRequest request
		HttpPost postRequest = new HttpPost("http://localhost:8080/RESTfulDemoApplication/user-management/users");
		
		//Set the API media type in http content-type header
		postRequest.addHeader("content-type", "application/xml");
		
		//Set the request post body
		StringEntity userEntity = new StringEntity(writer.getBuffer().toString());
		postRequest.setEntity(userEntity);
		 
		//Send the request; It will immediately return the response in HttpResponse object if any
		HttpResponse response = httpClient.execute(postRequest);
		
		//verify the valid error code first
		int statusCode = response.getStatusLine().getStatusCode();
		if (statusCode != 201) 
		{
			throw new RuntimeException("Failed with HTTP error code : " + statusCode);
		}
	}
	finally
	{
		//Important: Close the connect
		httpClient.getConnectionManager().shutdown();
	}
}

Drop me your comments on httpclient example of http post request and get request.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

6 thoughts on “Apache HttpClient GET and POST examples”

  1. Hi,
    Thanks for sharing the example on 2) GET API Example with Apache HttpClient.
    I have created a client program by following your example 2) GET API Example with Apache HttpClient.
    Please guide me what and how do I implement Junit for this scenario.

    Reply
    • In My client program, I am invoking some external service calls. third party URLs. I do not have web service provider implementation part.

      Reply
  2. Thanks for sharing the sample code on RESTFul service implementation & httpclient. I was writing the RESTFul services for the first time and your sample code really helped me a lot.

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.