VOOZH about

URL: https://www.javacodegeeks.com/2012/09/simple-rest-client-in-java.html

⇱ Simple REST client in Java - Java Code Geeks


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:
 
 

Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
and many more ....
I agree to the Terms and Privacy Policy

Thank you!

We will contact you soon.

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

Happy coding and don’t forget to share!

Reference: Simple REST client in java from our JCG partner Harsh Raval at the harryjoy blog.

Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Thank you!

We will contact you soon.

πŸ‘ Photo of Harsh Raval
Harsh Raval
September 11th, 2012Last Updated: January 9th, 2018
18 32,219 3 minutes read
Subscribe

This site uses Akismet to reduce spam. Learn how your comment data is processed.

18 Comments
Oldest
Newest Most Voted
13 years ago

The Fluent API which is part of the Http Client 4.x lib is also pretty good

3
Reply
Lokesh Bathija
12 years ago

This indeed is helpful. Thanks Harsh.

1
Reply
Prateek Arora
12 years ago

Your tutorial is really helpful but please give the link of the JAR’s to use along with the code.

0
Reply
Mohana Priya
12 years ago

Thanks Harsh. It is useful to me

0
Reply
11 years ago

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!

2
Reply
11 years ago

In section 2. the line for GET calls in XML and JSON format respectively, seems to have been switched.

0
Reply
Amit Dudeja
10 years ago

Its working ,Code is accurate….

0
Reply
vipul
10 years ago

Excellent Post.. one last stop to all query related rest api, Thanks Harsh, Keep posting good technical blog content.

0
Reply
Devz
10 years ago

Hi Thanks for the post. Its works just fine. I am using your HTTP get and post.

In your : ” sending simple string in post: ” How can I send source frame as source data? Thanks

0
Reply
Juan Moreno
10 years ago

Alchemy-HTTP is a really nice library for making Web calls from Java

https://github.com/SirWellington/alchemy-http

From the ReadMe:
Coffee myCoffee = http.go()
.get()
.expecting(Coffee.class)
.at(β€œhttp://aroma.tech/orders?orderNumber=99”);

0
Reply
Sergio Panti
10 years ago

Hi Thanks for the post. Excellent.

0
Reply
Sergio Panti
10 years ago

DefaultHttpClient is deprecated.

It is better to use HttpClientBuilder:

HttpClient httpClient= HttpClientBuilder.create().build();

1
Reply
Maisa
10 years ago

Hi!
It’s a clear post and helpful!
Thanks a lot!

0
Reply
suman
9 years ago

I am very new to java. Please let me know how to solve the issue . When i try to run below code , I get error import org.apache.http. cannot be resolved. How to overcome this. I have just typed in eclipse 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 myget1 { 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())… Read more Β»

0
Reply
Ash
9 years ago
Reply to  suman

@,
You need to add the libraries to your project first. Only then the imports will work.
The link to these libraries are mentioned at the very top of the post.

0
Reply
Shiv kumar Napit
8 years ago

I am getting HTTP 401 response while calling rest api. Actually the rest api which i am calling requires HTTP authentication. So, can anyone help me with how i can pass my authentication credentials in the request?

16
Reply
sanjay
8 years ago

i want a rest api call for https .. how certificate can enter into the picture?

0
Reply
Ran
8 years ago

Hi i am using REST API without JASON. I am using Put method to upload a document from java to SharePoint. how do i pass required metadata without Using JASON

0
Reply
Back to top button
Close
wpDiscuz