tags:

views:

170

answers:

6

Hi, everyone,

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? Can anyone help me. thank you.

+4  A: 

There are several RESTful APIs around. I would recommend Jersey;

https://jersey.dev.java.net/

Client API documentation is here;

https://jersey.dev.java.net/nonav/documentation/latest/client-api.html

Qwerky
The OP is not creating a RESTful application, he's making RESTful calls, i.e. like calling a Twitter API method resource.
The Elite Gentleman
Jersey provides a full featured, production quality client. Doesn't the Twitter API use OAuth? Good luck to the OP implementing that from scratch. Oh wait! Jersey already did it: http://developers.sun.com/identity/reference/techart/restwebservices.html
Qwerky
+1  A: 

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:

seanizer
A: 

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();
    }
}
jitter
There are some really good REST APIs around, I'd recommend using one rather than reinventing the wheel.
Qwerky
as I said: complicated as hell. (no, I did not downvote this, it's a perfectly valid solution)
seanizer
@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
I fully agree with Darrel Miller....
The Elite Gentleman
+2  A: 

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 that 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 as you can work as mentioned above.


Documentation on HttpClient: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/index.html

The Elite Gentleman
Don't reinvent the wheel, use one of the existing RESTful implementations.
Qwerky
It'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.
The Elite Gentleman
@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
@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.
The Elite Gentleman
@The Elite Gentleman, thank you.
Questions
You're welcome....
The Elite Gentleman
+1  A: 

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();
Joopiter
+2  A: 

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 = Client.create();
WebResource resource = c.resource("http://localhost:8080/someresource");

resource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE);

ClientResponse response = resource.post(ClientResponse.class, form);

if (response.getClientResponseStatus().getFamily() == Family.SUCCESSFUL) {
    System.out.println("Success! " + response.getStatus());
    System.out.println(response.getEntity(String.class));
} else {
    System.out.println("ERROR! " + response.getStatus());    
    System.out.println(response.getEntity(String.class));
}

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.

Avi Flax