I am going to make a RESTful call in Java. However, I don't know how to make the call. Do I need to use the URLConnection
or others?
-
It depends how you do rest calls in your application. Do you use a JaxRS implementation ? A particular one ? Are you doing requests manually ? – Colin Hebert Oct 12 '10 at 10:10
-
@Colin Hebert, thank you for your reply. But I have no ideas of the RESTful call. could you give me more information about different parts of the RESTful call. – Questions Oct 13 '10 at 02:00
-
checkout http restful client [click here](https://github.com/gsssoftwaresolution/easyrestfulclient) – Gaurav J Dec 20 '17 at 10:01
14 Answers
Update: It’s been almost 5 years since I wrote the answer below; today I have a different perspective.
99% of the time when people use the term REST, they really mean HTTP; they could care less about “resources”, “representations”, “state transfers”, “uniform interfaces”, “hypermedia”, or any other constraints or aspects of the REST architecture style identified by Fielding. The abstractions provided by various REST frameworks are therefore confusing and unhelpful.
So: you want to send HTTP requests using Java in 2015. You want an API that is clear, expressive, intuitive, idiomatic, simple. What to use? I no longer use Java, but for the past few years the Java HTTP client library that has seemed the most promising and interesting is OkHttp. Check it out.
You can definitely interact with RESTful web services by using URLConnection
or HTTPClient to code HTTP requests.
However, it's generally more desirable to use a library or framework which provides a simpler and more semantic API specifically designed for this purpose. This makes the code easier to write, read, and debug, and reduces duplication of effort. These frameworks generally implement some great features which aren't necessarily present or easy to use in lower-level libraries, such as content negotiation, caching, and authentication.
Some of the most mature options are Jersey, RESTEasy, and Restlet.
I'm most familiar with Restlet, and Jersey, let's look at how we'd make a POST
request with both APIs.
Jersey Example
Form form = new Form();
form.add("x", "foo");
form.add("y", "bar");
Client client = ClientBuilder.newClient();
WebTarget resource = client.target("http://localhost:8080/someresource");
Builder request = resource.request();
request.accept(MediaType.APPLICATION_JSON);
Response response = request.get();
if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
System.out.println("Success! " + response.getStatus());
System.out.println(response.getEntity());
} else {
System.out.println("ERROR! " + response.getStatus());
System.out.println(response.getEntity());
}
Restlet Example
Form form = new Form();
form.add("x", "foo");
form.add("y", "bar");
ClientResource resource = new ClientResource("http://localhost:8080/someresource");
Response response = resource.post(form.getWebRepresentation());
if (response.getStatus().isSuccess()) {
System.out.println("Success! " + response.getStatus());
System.out.println(response.getEntity().getText());
} else {
System.out.println("ERROR! " + response.getStatus());
System.out.println(response.getEntity().getText());
}
Of course, GET requests are even simpler, and you can also specify things like entity tags and Accept
headers, but hopefully these examples are usefully non-trivial but not too complex.
As you can see, Restlet and Jersey have similar client APIs. I believe they were developed around the same time, and therefore influenced each other.
I find the Restlet API to be a little more semantic, and therefore a little clearer, but YMMV.
As I said, I'm most familiar with Restlet, I've used it in many apps for years, and I'm very happy with it. It's a very mature, robust, simple, effective, active, and well-supported framework. I can't speak to Jersey or RESTEasy, but my impression is that they're both also solid choices.

- 50,872
- 9
- 47
- 64
-
2But still a great post. And I have to agree with "99% of the time when people use the term REST, they really mean HTTP; ...The abstractions provided by various REST frameworks are therefore confusing and unhelpful." – AlexD Nov 02 '17 at 14:31
-
2In your Jersey example, where/how does the Form object get used? It's created, but it doesn't appear to add anything to the example. – splungebob Jun 19 '18 at 13:47
If you are calling a RESTful service from a Service Provider (e.g Facebook, Twitter), you can do it with any flavour of your choice:
If you don't want to use external libraries, you can use java.net.HttpURLConnection
or javax.net.ssl.HttpsURLConnection
(for SSL), but that is call encapsulated in a Factory type pattern in java.net.URLConnection
.
To receive the result, you will have to connection.getInputStream()
which returns you an InputStream
. You will then have to convert your input stream to string and parse the string into it's representative object (e.g. XML, JSON, etc).
Alternatively, Apache HttpClient (version 4 is the latest). It's more stable and robust than java's default URLConnection
and it supports most (if not all) HTTP protocol (as well as it can be set to Strict mode). Your response will still be in InputStream
and you can use it as mentioned above.
Documentation on HttpClient: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/index.html

- 87,898
- 29
- 167
- 228
-
7Don't reinvent the wheel, use one of the existing RESTful implementations. – Qwerky Oct 12 '10 at 10:39
-
16It's not reinventing the wheel, I'm saying you can use whatever `flavour` you want. Some want the default `URLConnection`, some wants `HttpClient`. Either way, it's there for you to use. – Buhake Sindi Oct 12 '10 at 10:43
-
@The Elite Gentleman, thank you for your reply. After checked the all of the library, I want to use the Apache HttpClient, would you mind to give me more reference about this one? – Questions Oct 13 '10 at 02:53
-
@Questions, the link to the HttpClient 4 examples seems to be broken, so if you have any questions (pun intended...lol), let me know....I deal with it almost daily. – Buhake Sindi Oct 13 '10 at 09:41
-
Please show example code of how to use these classes, rather than just noting their existence – Jonathan Nov 21 '18 at 19:15
-
@Jonathan - I'd recommend going to the link provided and looking at code examples provided in the documentation for the actual library. Not only is it going to be more inclusive, but thorough and accurate as well... – Danny Bullis Nov 24 '18 at 20:17
This is very complicated in java, which is why I would suggest using Spring's RestTemplate
abstraction:
String result =
restTemplate.getForObject(
"http://example.com/hotels/{hotel}/bookings/{booking}",
String.class,"42", "21"
);
Reference:
- Spring Blog: Rest in Spring 3 (RestTemplate)
- Spring Reference: Accessing RESTful services on the Client
- JavaDoc:
RestTemplate

- 292,901
- 67
- 465
- 588
-
According to this - https://stackoverflow.com/questions/42365266/call-another-rest-api-from-my-server-in-spring-boot - [RestTemplate](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html) will be deprecated in a future version, use the more modern alternative [WebClient](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/reactive/function/client/WebClient.html) – kaushalpranav Oct 13 '21 at 13:09
-
1@kaushalpranav my answer was true at the time, but things change. I suggest you add your own answer with WebClient – Sean Patrick Floyd Oct 19 '21 at 18:09
-
True. I used `RestTemplate` recently in my projects and didn't know of `WebClient`, so just wanted to direct people coming here to the newer alternative. – kaushalpranav Oct 19 '21 at 22:55
If you just need to make a simple call to a REST service from java you use something along these line
/*
* Stolen from http://xml.nig.ac.jp/tutorial/rest/index.html
* and http://www.dr-chuck.com/csev-blog/2007/09/calling-rest-web-services-from-java/
*/
import java.io.*;
import java.net.*;
public class Rest {
public static void main(String[] args) throws IOException {
URL url = new URL(INSERT_HERE_YOUR_URL);
String query = INSERT_HERE_YOUR_URL_PARAMETERS;
//make connection
URLConnection urlc = url.openConnection();
//use post mode
urlc.setDoOutput(true);
urlc.setAllowUserInteraction(false);
//send query
PrintStream ps = new PrintStream(urlc.getOutputStream());
ps.print(query);
ps.close();
//get result
BufferedReader br = new BufferedReader(new InputStreamReader(urlc
.getInputStream()));
String l = null;
while ((l=br.readLine())!=null) {
System.out.println(l);
}
br.close();
}
}

- 53,475
- 11
- 111
- 124
-
1There are some really good REST APIs around, I'd recommend using one rather than reinventing the wheel. – Qwerky Oct 12 '10 at 10:21
-
1as I said: complicated as hell. (no, I did not downvote this, it's a perfectly valid solution) – Sean Patrick Floyd Oct 12 '10 at 10:22
-
4@Qwerky Client side API libraries are usually a violation of REST constraints. They introduce far too much coupling. Using a good HTTP library is a much better option in the long term. – Darrel Miller Oct 12 '10 at 11:45
There are several RESTful APIs around. I would recommend Jersey;
Client API documentation is here;
https://jersey.java.net/documentation/latest/index.html
Update
Location for the OAuth docs in the comment below is a dead link and has moved to https://jersey.java.net/nonav/documentation/latest/security.html#d0e12334

- 18,217
- 6
- 44
- 80
-
7The OP is not creating a RESTful application, he's making RESTful calls, i.e. like calling a Twitter API method resource. – Buhake Sindi Oct 12 '10 at 10:23
-
@Qwerky - I think it'd be helpful to include why you recommend Jersey in your answer. – Danny Bullis Nov 24 '18 at 20:19
I want to share my personal experience, calling a REST WS with Post JSON call:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.URL;
import java.net.URLConnection;
public class HWS {
public static void main(String[] args) throws IOException {
URL url = new URL("INSERT YOUR SERVER REQUEST");
//Insert your JSON query request
String query = "{'PARAM1': 'VALUE','PARAM2': 'VALUE','PARAM3': 'VALUE','PARAM4': 'VALUE'}";
//It change the apostrophe char to double quote char, to form a correct JSON string
query=query.replace("'", "\"");
try{
//make connection
URLConnection urlc = url.openConnection();
//It Content Type is so important to support JSON call
urlc.setRequestProperty("Content-Type", "application/xml");
Msj("Conectando: " + url.toString());
//use post mode
urlc.setDoOutput(true);
urlc.setAllowUserInteraction(false);
//send query
PrintStream ps = new PrintStream(urlc.getOutputStream());
ps.print(query);
Msj("Consulta: " + query);
ps.close();
//get result
BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
String l = null;
while ((l=br.readLine())!=null) {
Msj(l);
}
br.close();
} catch (Exception e){
Msj("Error ocurrido");
Msj(e.toString());
}
}
private static void Msj(String texto){
System.out.println(texto);
}
}

- 839
- 9
- 15

- 99
- 1
- 1
You can check out the CXF. You can visit the JAX-RS Article here
Calling is as simple as this (quote):
BookStore store = JAXRSClientFactory.create("http://bookstore.com", BookStore.class);
// (1) remote GET call to http://bookstore.com/bookstore
Books books = store.getAllBooks();
// (2) no remote call
BookResource subresource = store.getBookSubresource(1);
// {3} remote GET call to http://bookstore.com/bookstore/1
Book b = subresource.getDescription();

- 525
- 3
- 8
- 18
Most Easy Solution will be using Apache http client library. refer following sample code.. this code uses basic security for authenticating.
Add following Dependency.
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.4</version> </dependency>
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
Credentials credentials = new UsernamePasswordCredentials("username", "password");
credentialsProvider.setCredentials(AuthScope.ANY, credentials);
HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
HttpPost request = new HttpPost("https://api.plivo.com/v1/Account/MAYNJ3OT/Message/");HttpResponse response = client.execute(request);
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
textView = textView + line;
}
System.out.println(textView);

- 712
- 1
- 14
- 29
-
you provided the maven dependencies, but you didn't include any import statements. This was *almost* useful. – barrypicker Jul 30 '20 at 15:17
-
1
Indeed, this is "very complicated in Java":
From: https://jersey.java.net/documentation/latest/client.html
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://foo").path("bar");
Invocation.Builder invocationBuilder = target.request(MediaType.TEXT_PLAIN_TYPE);
Response response = invocationBuilder.get();
I see many answers, here's what we are using in 2020 WebClient, and BTW RestTemplate is going to get deprecated. (can check this) RestTemplate going to be deprecated

- 107
- 4
- 12
Simple and synchronous version of G. Ciardini with modern Java:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(create("https://some-rest-url/path"))
//.headers(...)
.build();
HttpResponse<String> httpResponse = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(httpResponse.body());

- 3,795
- 4
- 32
- 39
You can use Async Http Client (The library also supports the WebSocket Protocol) like that:
String clientChannel = UriBuilder.fromPath("http://localhost:8080/api/{id}").build(id).toString();
try (AsyncHttpClient asyncHttpClient = new AsyncHttpClient())
{
BoundRequestBuilder postRequest = asyncHttpClient.preparePost(clientChannel);
postRequest.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
postRequest.setBody(message.toString()); // returns JSON
postRequest.execute().get();
}

- 7,260
- 3
- 53
- 56
The following is an example of a GET request that prints the response body as a String with HttpRequest:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://example.org/"))
.build();
client.sendAsync(request, BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println)
.join();
If you need to set the header you could use the following method inside the HttpRequest.Builder
:
.setHeader("api-key", "value")

- 1,210
- 1
- 17
- 32
Here is a utility class I use for calling some internal APIs (Sept 2022). All core java except for Gson for the Json de/serialization. POST and GET.
package com.somepackagename.utils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.Map;
public class HTTPCaller {
private final String BEARER_TOKEN;
private static Gson gson = new GsonBuilder().setPrettyPrinting().serializeSpecialFloatingPointValues().create();
public HTTPCaller(String bearerToken) {
this.BEARER_TOKEN = bearerToken;
}
public Map<String, Object> post(String endpoint, String jsonPayload, Map<String, String> headers)
throws IOException, URISyntaxException, InterruptedException {
HttpRequest.Builder reqBuilder = HttpRequest.newBuilder();
if (headers != null) {
for (Map.Entry<String, String> header : headers.entrySet()) {
reqBuilder.header(header.getKey(), header.getValue());
}
}
//always add these anyway, or not
reqBuilder.header("content-type", "application/json")
.header("Authorization", "Bearer " + BEARER_TOKEN);
HttpRequest request = reqBuilder
.uri(new URI(endpoint))
.POST(HttpRequest.BodyPublishers.ofByteArray(jsonPayload.getBytes()))
.build();
HttpResponse<String> response = HttpClient.newBuilder()
.build()
.send(request, java.net.http.HttpResponse.BodyHandlers.ofString());
String responseBody = response.body();
Map<String, Object> output = (Map<String, Object>) gson.fromJson(responseBody, HashMap.class);
return output;
}
public Map<String, Object> get(String endpoint) throws Exception {
HttpRequest.Builder reqBuilder = HttpRequest.newBuilder();
//always add these anyway
reqBuilder.header("content-type", "application/json")
.header("Authorization", "Bearer " + BEARER_TOKEN);
HttpRequest request = reqBuilder
.uri(new URI(endpoint))
.GET()
.build();
HttpResponse<String> response = HttpClient.newBuilder()
.build()
.send(request, java.net.http.HttpResponse.BodyHandlers.ofString());
String responseBody = response.body();
Map<String, Object> output = (Map<String, Object>) gson.fromJson(responseBody, HashMap.class);
return output;
}
}

- 3,844
- 5
- 20
- 42