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
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.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

  • Pingback: check this()

  • Pingback: communications electrician los angeles()

  • Pingback: house blue()

  • Pingback: plumbing supply store near me()

  • Pingback: locksmith des moines()

  • Pingback: electrician 2015()

  • Pingback: water ionizer pay plan loans()

  • Pingback: pay per day loans plan()

  • Pingback: parking()

  • Pingback: laan her og nu()

  • Pingback: bedste laan lige nu()

  • Pingback: parking()

  • Pingback: kangen water()

  • Pingback: water ionizer()

  • Pingback: streaming movies()

  • Pingback: tv online, online tv()

  • Pingback: watch tv show episodes()

  • Pingback: watch free movies online()

  • Pingback: how to loose weight()

  • Pingback: Blue Coaster33()

  • Pingback: JAX-RS TUTORIALS | BUYWORKSELL()

  • 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\”:\”[email protected]\”,\”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] Running:
    /private/var/folders/lt/jxr2xw295d98wq_9xfgfmdjrg_7q0b/T/testng-eclipse-1291210530/testng-customsuite.xml

    http://test-www.nature.com/api/users
    FAILED: createNewUser
    Creates a new user on Nature.com
    java.lang.RuntimeException: Failed : HTTP error code : 422
    at com.nature.foxtrot.tests.RestDemo.createNewUser(RestDemo.java:67)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
    at org.testng.TestRunner.privateRun(TestRunner.java:767)
    at org.testng.TestRunner.run(TestRunner.java:617)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
    at org.testng.SuiteRunner.run(SuiteRunner.java:240)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
    at org.testng.TestNG.run(TestNG.java:1057)
    at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)
    ————————————

  • Abhisek

    Hi MKYong,

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

    Regards

    • ram

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

  • tina

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

  • 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

    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, String arg1)
    throws java.security.cert.CertificateException
    {
    // TODO Auto-generated method stub

    }

    @Override
    public void checkServerTrusted(
    java.security.cert.X509Certificate[] arg0, String arg1)
    throws java.security.cert.CertificateException {
    // TODO Auto-generated method stub

    }
    };
    ctx.init(null, new TrustManager[] { tm }, null);
    SSLSocketFactory ssf = new SSLSocketFactory(ctx);
    ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    ClientConnectionManager ccm = base.getConnectionManager();
    SchemeRegistry sr = ccm.getSchemeRegistry();
    sr.register(new Scheme(“https”, ssf, 8443));
    return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
    return null;
    }
    }

    // http://localhost:8080/RESTfulExample/json/product/post

    public static void main(String[] args) {

    Properties logProp = new Properties();
    try {
    String username = “”;
    String password = “”;
    logProp.load(new FileInputStream(“login.properties”));
    if (logProp != null) {
    username = logProp.getProperty(“username”);
    password = logProp.getProperty(“password”);
    }
    if (username.equals(“”) && password.equals(“”)) {
    log.error(“the username and password fields are empty”);
    } else {
    HttpClient httpClient = new DefaultHttpClient();

    httpClient = wrapClient(httpClient);

    DefaultHttpClient httpClient1 = (DefaultHttpClient) httpClient;

    httpClient1.getCredentialsProvider().setCredentials(
    new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT,
    AuthScope.ANY_REALM, “basic”),
    new UsernamePasswordCredentials(“mifos”, “password”));

    JSONObject object = new JSONObject();
    object.put(“serviceCode”, “ashok1″);
    object.put(“serviceDescription”, “reddy2″);
    object.put(“serviceType”, new Long(101));

    System.out.println(“————” + object.toString());

    StringEntity se = new StringEntity(object.toString());

    HttpPost postRequest1 = new HttpPost(“https://localhost:8443″
    + “/mifosng-provider/api/v1/servicemasters”);

    postRequest1.setHeader(“Content-Type”, “application/json”);
    //postRequest1.setHeader(“tenantIdentifier”, “default”);
    postRequest1.addHeader(“X-Mifos-Platform-TenantId”, “default”);
    postRequest1.setEntity(se);

    HttpResponse response1 = httpClient1.execute(postRequest1);
    if (response1.getStatusLine().getStatusCode() != 200) {
    log.error(“Failed : HTTP error code : ”
    + response1.getStatusLine().getStatusCode());
    return;
    }
    BufferedReader br1 = new BufferedReader(new InputStreamReader(
    (response1.getEntity().getContent())));

    String output1;
    System.out.println(“Output from Server …. \n”);
    log.info(“Output from Server …. \n”);
    while ((output1 = br1.readLine()) != null) {

    log.info(output1);
    }

    httpClient1.getConnectionManager().shutdown();
    httpClient.getConnectionManager().shutdown();

    }

    } catch (MalformedURLException e) {

    log.error(“Exceptions happen!”, e);
    } catch (IOException e) {
    log.error(“Logging not enabled”, e);
    log.error(“Exceptions happen!”, e);

    } catch (Exception e) {

    log.error(“Exceptions happen!”, e);

    }
    }
    }

  • 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

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

  • 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.

  • 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

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

  • 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

  • Pingback: AMIS Technology blog » Create simple Java application to post JSON message to CometD Bayeux Channel using Apache HttpClient and Maven style NetBeans project()

  • Pingback: Create simple Java application to post JSON message to CometD Bayeux Channel using Apache HttpClient and Maven style NetBeans project « AMIS Technology blog()