Restful Call in Java
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? 3 12 Answers Update: It’s...
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?
12 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.
Must Read
Jersey Example
Form form = new Form();
form.add("x", "foo");
form.add("y", "bar");
Client client = ClientBuilder.newClient();
WebTarget resource = client.target("");
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());
}