GET/POST request with Apache HttpClient

  • 27 January 2017
  • ADM

 

GET/POST request with Apache HttpClient - images/logos/java.jpg

 

This article will cover how to send GET and POST requests using Apache HttpClient.

First, we need a test server and for this, I will use httpbin.org. This test server contains a lot of useful endpoints for testing. In this tutorial will use 2 of them:

For the User-Agent header, I will use a random agent picked up from useragentstring.com

For Maven users add the Apache HttpClient dependency:

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

For non-maven users, you need to download the jar files and attached manually to the project.

Example

For POST you can setup the parameters in different ways.

For String body, you can use StringEntity class

StringEntity body = new StringEntity("Text to be send.");
request.setEntity(body);

For more complex data you can use a list with parameters and add the parameters using UrlEncodedFormEntity class.

List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("user", "admfactory"));
urlParameters.add(new BasicNameValuePair("password", "supersecret"));
urlParameters.add(new BasicNameValuePair("email", "admin@admfactory.com"));

request.setEntity(new UrlEncodedFormEntity(urlParameters));

Full Example

package com.admfactory.http;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;

public class HttpClientExample {

    private static final String USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36";

    public void get(String url, String params) throws Exception {
	HttpClient client = HttpClientBuilder.create().build();
	HttpGet request = new HttpGet(url);
	request.addHeader("User-Agent", USER_AGENT);
	HttpResponse response = client.execute(request);

	int responseCode = response.getStatusLine().getStatusCode();
	System.out.println("'GET' request to URL : " + url);
	System.out.println("Response Code : " + responseCode);

	System.out.println("Response Body : ");

	BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

	StringBuffer content = new StringBuffer();
	String line = "";
	while ((line = rd.readLine()) != null) {
	    content.append(line);
	}

	System.out.println(content);
    }

    public void post(String url, String params) throws Exception {
	HttpClient client = HttpClientBuilder.create().build();
	HttpPost request = new HttpPost(url);
	request.addHeader("User-Agent", USER_AGENT);

	StringEntity body = new StringEntity(params);
	request.setEntity(body);

	HttpResponse response = client.execute(request);

	int responseCode = response.getStatusLine().getStatusCode();
	System.out.println("'POST' request to URL : " + url);
	System.out.println("Response Code : " + responseCode);

	System.out.println("Response Body : ");

	BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

	StringBuffer content = new StringBuffer();
	String line = "";
	while ((line = rd.readLine()) != null) {
	    content.append(line);
	}

	System.out.println(content);
    }

    public static void main(String[] args) {
	try {
	    System.out.println("GET / POST example using Apache HttpClient");
	    System.out.println();

	    HttpClientExample example = new HttpClientExample();
	    String getUrl = "http://httpbin.org/get";

	    example.get(getUrl, "param1=123&param2=abc");
	    System.out.println();

	    String postUrl = "http://httpbin.org/post";
	    example.post(postUrl, "param3=345&param4=ert");

	} catch (Exception e) {
	    e.printStackTrace();
	}
    }
}

Output

GET / POST example using Apache HttpClient

'GET' request to URL : http://httpbin.org/get
Response Code : 200
Response Body : 
{  "args": {},   "headers": {    "Accept-Encoding": "gzip,deflate",     "Host": "httpbin.org",     "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36"  },   "url": "http://httpbin.org/get"}

'POST' request to URL : http://httpbin.org/post
Response Code : 200
Response Body : 
{  "args": {},   "data": "param3=345&param4=ert",   "files": {},   "form": {},   "headers": {    "Accept-Encoding": "gzip,deflate",     "Content-Length": "21",     "Content-Type": "text/plain; charset=ISO-8859-1",     "Host": "httpbin.org",     "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36"  },   "json": null,   "url": "http://httpbin.org/post"}

Note: Your response will be longer that my output. I removed some data that contains my IP address.

 

References