Simple REST client in java

Today most of the mobile applications that used to communicate to some server use REST services. These services are also common practice to use with JavaScript or jQuery. Right now I know 2 ways to create client for REST service in java and in this article I will try to demonstrate both the ways I know hoping that it will help someone in some way.

1. Using Apache HttpClient

The Apache HttpClient library simplifies handling HTTP requests. To use this library you have to download the binaries with dependencies from their website.
Here is the code for HTTP GET method:

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.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class Test {
	public static void main(String[] args) throws ClientProtocolException, IOException {
		HttpClient client = new DefaultHttpClient();
		HttpGet request = new HttpGet("http://restUrl");
		HttpResponse response = client.execute(request);
		BufferedReader rd = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
		String line = "";
		while ((line = rd.readLine()) != null) {
		  System.out.println(line);
		}
	}
}

And for Post method; for sending simple string in post:

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.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
public class Test {
	public static void main(String[] args) throws ClientProtocolException, IOException {
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost("http://restUrl");
		StringEntity input = new StringEntity("product");
		post.setEntity(input);
		HttpResponse response = client.execute(post);
		BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
		String line = "";
		while ((line = rd.readLine()) != null) {
			System.out.println(line);
		}
	}
}

You can also send full JSON or XML of a POJO by putting String representing JSON or XML as a parameter of StringEntity and then set the input content type. Something like this:

StringEntity input = new StringEntity("{\"name1\":\"value1\",\"name2\":\"value2\"}"); //here instead of JSON you can also have XML
input.setContentType("application/json");

For JSON you can use JSONObject to create string representation of JSON.

JSONObject json = new JSONObject();
json.put("name1", "value1");
json.put("name2", "value2");
StringEntity se = new StringEntity( json.toString());

And for sending multiple parameter in post request:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
public class Test {
	public static void main(String[] args) throws ClientProtocolException, IOException {
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost("http://restUrl");
		List nameValuePairs = new ArrayList(1);
		nameValuePairs.add(new BasicNameValuePair("name", "value")); //you can as many name value pair as you want in the list.
		post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		HttpResponse response = client.execute(post);
		BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
		String line = "";
		while ((line = rd.readLine()) != null) {
			System.out.println(line);
		}
	}
}

2. Using Jersey

Jersey is the reference implementation forJSR-311 specification, the specification of REST support in Java. Jersey contains basically a REST server and a REST client. it provides a library to communicate with the server producing REST services. For http get method:

import java.io.IOException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import org.apache.http.client.ClientProtocolException;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
public class Test {
	public static void main(String[] args) throws ClientProtocolException, IOException {
		ClientConfig config = new DefaultClientConfig();
		Client client = Client.create(config);
		WebResource service = client.resource(UriBuilder.fromUri("http://restUrl").build());
		// getting XML data
		System.out.println(service. path("restPath").path("resourcePath").accept(MediaType.APPLICATION_JSON).get(String.class));
		// getting JSON data
		System.out.println(service. path("restPath").path("resourcePath").accept(MediaType.APPLICATION_XML).get(String.class));
	}
}

There are also other media formats in which you can get the response like PLAIN or HTML.
And for HTTP POST method:

import java.io.IOException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriBuilder;
import org.apache.http.client.ClientProtocolException;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.core.util.MultivaluedMapImpl;
public class Test {
	public static void main(String[] args) throws ClientProtocolException, IOException {
		ClientConfig config = new DefaultClientConfig();
		Client client = Client.create(config);
		WebResource webResource = client.resource(UriBuilder.fromUri("http://restUrl").build());
		MultivaluedMap formData = new MultivaluedMapImpl();
		formData.add("name1", "val1");
		formData.add("name2", "val2");
		ClientResponse response = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).post(ClientResponse.class, formData);
		System.out.println("Response " + response.getEntity(String.class));
	}
}

If you are using your POJO in the POST then you can do something like following:

ClientResponse response = webResource.path("restPath").path("resourcePath").
type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, myPojo);
System.out.println("Response " + response.getEntity(String.class));

Here myPojo is an instance of custom POJO class.
You can also use Form class from Jersey to submit multiple parameters in POST request:

import java.io.IOException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import org.apache.http.client.ClientProtocolException;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.representation.Form;
public class Test {
	public static void main(String[] args) throws ClientProtocolException, IOException {
		ClientConfig config = new DefaultClientConfig();
		Client client = Client.create(config);
		WebResource service = client.resource(UriBuilder.fromUri("http://restUrl").build());
		Form form = new Form();
		form.add("name1", "value1");
		form.add("name2", "value1");
		ClientResponse response = service.path("restPath").path("resourcePath").
		type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, form);
		System.out.println("Response " + response.getEntity(String.class));
	}
}

Let me know if you find any difficulty while using these code samples. Feel free to comment. :)

About these ads

About harryjoy
A passionate self-taught software developer. Currently working as Software Engineer in an IT company located in INDIA.

14 Responses to Simple REST client in java

  1. Pingback: SOAP Client in java « harryjoy

  2. Pingback: Simple REST client in java | Java EE 6 Development | Scoop.it

  3. Pingback: JavaPins

  4. Pingback: Simple REST client in java | back2dev | Scoop.it

  5. Imran says:

    Reblogged this on Imranakbar's Blog and commented:
    A simple example developing a Rest Client in Java

  6. Brendon says:

    Thanks a lot, really helped.

  7. Subcomandante_M says:

    Nice, thx a lot ….

  8. Pingback: Confluence: Software Requirement Specifications

  9. Shannara says:

    Thanks for the code, but you seem to be using something other then Jersey. The Jersey name space is :

    org.glassfish.jersey.*;

    And there is no client in there at all …

  10. Pingback: HTTP post with json data using java

  11. Good Nature says:

    Try looking at http-rest-client

    https://github.com/g00dnatur3/http-rest-client

    Here is a simple example:

    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);

    Cheers!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 70 other followers

%d bloggers like this: