Apache HttpClient can be used to send HTTP requests from client code to server. In our last tutorial, we saw how to use HttpURLConnection to perform GET and POST HTTP request operations from java program itself. Today we will take the same example project but use Apache HttpClient to perform GET and POST request operations.
Apache HttpClient
For the sake of understanding the GET and POST request details, I would strongly suggest you to have a look at the earlier example too. Apache HttpClient is very widely used for sending HTTP requests from java program itself. If you are using Maven, then you can add below dependencies and it will include all other required dependencies for using Apache HttpClient.
1 2 3 4 5 6 7 |
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.4</version> </dependency> |
However if you are not using Maven, then need to add following jars in your project build path for it to work.
- httpclient-4.4.jar
- httpcore-4.4.jar
- commons-logging-1.2.jar
- commons-codec-1.9.jar
If you are using some other version of Apache HttpClient and not using Maven, then just create a temporary Maven project to get the list of compatible jars, as shown in image below.
Now just copy the jars to your project lib directory, it will save you from any compatibility issues as well as it will save time in finding jars and downloading from internet.
Now that we have all the required dependencies, below are the steps for using Apache HttpClient to send GET and POST requests.
- Create instance of
CloseableHttpClient
using helper classHttpClients
. - Create
HttpGet
orHttpPost
instance based on the HTTP request type. - Use addHeader method to add required headers such as User-Agent, Accept-Encoding etc.
- For POST, create list of
NameValuePair
and add all the form parameters. Then set it to the HttpPost entity. - Get
CloseableHttpResponse
by executing the HttpGet or HttpPost request. - Get required details such as status code, error information, response html etc from the response.
- Finally close the apache
HttpClient
resource.
Below is the final program we have showing how to use Apache HttpClient for performing HTTP GET and POST requests in a java program itself.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
package com.journaldev.utils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; public class ApacheHttpClientExample { private static final String USER_AGENT = "Mozilla/5.0"; private static final String GET_URL = "https://localhost:9090/SpringMVCExample"; private static final String POST_URL = "https://localhost:9090/SpringMVCExample/home"; public static void main(String[] args) throws IOException { sendGET(); System.out.println("GET DONE"); sendPOST(); System.out.println("POST DONE"); } private static void sendGET() throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(GET_URL); httpGet.addHeader("User-Agent", USER_AGENT); CloseableHttpResponse httpResponse = httpClient.execute(httpGet); System.out.println("GET Response Status:: " + httpResponse.getStatusLine().getStatusCode()); BufferedReader reader = new BufferedReader(new InputStreamReader( httpResponse.getEntity().getContent())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = reader.readLine()) != null) { response.append(inputLine); } reader.close(); // print result System.out.println(response.toString()); httpClient.close(); } private static void sendPOST() throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(POST_URL); httpPost.addHeader("User-Agent", USER_AGENT); List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); urlParameters.add(new BasicNameValuePair("userName", "Pankaj Kumar")); HttpEntity postParams = new UrlEncodedFormEntity(urlParameters); httpPost.setEntity(postParams); CloseableHttpResponse httpResponse = httpClient.execute(httpPost); System.out.println("POST Response Status:: " + httpResponse.getStatusLine().getStatusCode()); BufferedReader reader = new BufferedReader(new InputStreamReader( httpResponse.getEntity().getContent())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = reader.readLine()) != null) { response.append(inputLine); } reader.close(); // print result System.out.println(response.toString()); httpClient.close(); } } |
When we run above program, we get similar output html as received in the browser.
1 2 3 4 5 6 7 8 |
GET Response Status:: 200 <html><head> <title>Home</title></head><body><h1> Hello world! </h1><P> The time on the server is March 7, 2015 1:01:22 AM IST. </P></body></html> GET DONE POST Response Status:: 200 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>User Home Page</title></head><body><h3>Hi Pankaj Kumar</h3></body></html> POST DONE |
That’s all for Apache HttpClient example, it contains a lot of utility methods that you can use. So I would suggest you to check them out for better understanding.