- RESTful Java client with Apache HttpClient
- 1. Get Apache HttpClient
- 2. GET Request
- 3. POST Request
- Download Source Code
- References
- Comments
- How to send POST HTTP request and get HTTP response in Java with Apache Http Client
- POST HTTP Request
- HTTP Request Headers
- Apache HttpClient
- HttpResponse. response.getEntity().getContent()
- Convert response.getEntity().getContent() from JSON to object
- Response Code
- Apache HttpClient — complete example
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.
1. Get Apache HttpClient
Apache HttpClient is available in Maven central repository, just declares it in your Maven pom.xml file.
org.apache.httpcomponents httpclient 4.1.1
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(); >> >
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(""); 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 from Server . Product created : Product [name=iPad 4, qty=100]
Download Source Code
References
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.
Comments
how to get user details using web service in java swing project
Try looking at http-rest-client
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);
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 […]RestClient client = RestClient.builder().build();
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
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));
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();
>
What is the equivalent of @Consumes of JAX-RS in Spring MVC?
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.
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);
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 …?
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
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 […]Bad tutorial nothing explained wtf is “application/json”. If you mke tutorials you have to explain 🙁
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
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!
I have created a simple post request, but it’s returning 422 status code:
public void createNewUser()
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(
“http://test-www.nature.com/api/users”);
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);
>
> catch (MalformedURLException e)
>
———————–Error——-
[TestNG] Running:
/private/var/folders/lt/jxr2xw295d98wq_9xfgfmdjrg_7q0b/T/testng-eclipse-1291210530/testng-customsuite.xml
How to send POST HTTP request and get HTTP response in Java with Apache Http Client
Apache Http Client alows us to send Http requests and get Http responses.
Find other posts about GET, PUT and DELETE requests.
POST HTTP Request
This is how to create a simple POST HTTP request
HttpPost post = new HttpPost(url);
Here url is the url of the web service endpoint or the url of the web site page. Let’s assume we have some user service and we want to create a new user the url would be https://www.user-service-example.com/api/users . We should send a request with the new user info in JSON format.
HTTP Request Headers
To do that we have to set headers for the request. Headers is the array that contains key-value pairs. In our case headers look like this
Header headers[] = new BasicHeader("Content-type", "application/json"), new BasicHeader("Accept", "application/json") >; post.setHeaders(headers);
post.setHeader("Content-type", "application/json"); post.setHeader("Accept", "application/json"
That means that the request payload is in JSON format and we expect a response to be also in JSON format.
Now we should set the payload.
Gson gson = new Gson(); String json = gson.toJson(new User("John", "Doe", "john.doe@yahoogmail.com")); post.setEntity(new StringEntity(json));
Apache HttpClient
Now you have to create a HTTP client, send POST request, get a response and close.
HttpClient client = HttpClients.custom().build(); HttpResponse response = client.execute(post);
HttpResponse. response.getEntity().getContent()
We access the Http response content with response.getEntity().getContent().
String result = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8); response.getEntity().getContent().close();
If you expect the response body (response.getEntity().getContent()) to be a JSON then you can convert that to a Java object.
Convert response.getEntity().getContent() from JSON to object
User user = gson.fromJson(result, User.class);
Response Code
You also can verify the response code if you need.
int responseCode = response.getStatusLine().getStatusCode(); String statusPhrase = response.getStatusLine().getReasonPhrase();
Apache HttpClient — complete example
HttpPost post = new HttpPost(url); Header headers[] = new BasicHeader("Content-type", "application/json"), new BasicHeader("Accept", "application/json") >; post.setHeaders(headers); Gson gson = new Gson(); String json = gson.toJson(new User("John", "Doe", "john.doe@yahoogmail.com")); post.setEntity(new StringEntity(json)); HttpClient client = HttpClients.custom().build(); HttpResponse response = client.execute(post); String result = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8); User createdUser = gson.fromJson(result, User.class); int responseCode = response.getStatusLine().getStatusCode(); String statusPhrase = response.getStatusLine().getReasonPhrase(); response.getEntity().getContent().close();
You may also find these posts interesting: