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 = 
URL url = new URL(uri);
HttpURLConnection connection = 
    (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Accept", "application/xml");

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

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 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")

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

        // Get response as List
        List customers = resource.path("findCustomersByCity/Any%20Town")
                .get(new GenericType>(){});



Post a Comment