Wednesday 13 March 2013

REST WebService Clients

Leave a Comment
Using a Web Browser as the Client

The easiest way to test our RESTful service is using your favourite web browser.  Simply enter the URL and the browser will render the result as XML.


Using Java SE

There currently isn't a standard set of APIs yet for interacting with JAX-RS.  However your Java SE install already has all the necessary APIs.
String uri = 
    "http://localhost:8080/CustomerService/rest/customers/1";
URL url = new URL(uri);
HttpURLConnection connection = 
    (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");

JAXBContext jc = JAXBContext.newInstance(Customer.class);
InputStream xml = connection.getInputStream();
Customer customer = 
    (Customer) jc.createUnmarshaller().unmarshal(xml);

connection.disconnect();
Using Implmentation Specific APIs 

 While there isn't a standard set of APIs to interact with JAX-RS services, implementations like Jersey do provide APIs that are easier to use than standard Java SE.
import java.util.List;
import javax.ws.rs.core.MediaType;
import org.example.Customer;
import com.sun.jersey.api.client.*;

public class JerseyClient {

    public static void main(String[] args) {
        Client client = Client.create();
        WebResource resource = client.resource("http://localhost:8080/CustomerService/rest/customers");

        // Get response as String
        String string = resource.path("1")
            .accept(MediaType.APPLICATION_XML)
                .get(String.class);
        System.out.println(string);

        // Get response as Customer
        Customer customer = resource.path("1")
            .accept(MediaType.APPLICATION_XML)
                .get(Customer.class);
        System.out.println(customer.getLastName() + ", "+ customer.getFirstName());

        // Get response as List
        List customers = resource.path("findCustomersByCity/Any%20Town")
            .accept(MediaType.APPLICATION_XML)
                .get(new GenericType>(){});
        System.out.println(customers.size());
    }

}

0 comments:

Post a Comment