RESTful WS using Jersey: Client request.

Jersey provides a client library which includes functions to request a resource. This tutorial show some basic requests from a client.

  1. We continue with the same Java project of the previous tutorial. (you can also create a new Java project for this tutorial)
  2. Create a new Java package, name it my.second.rest.
  3. Create a new Java class under this package, name it ClientRequest.
  4. Edit the ClientRequest class as following:

    package my.second.rest;
     
    import javax.ws.rs.core.MediaType;
    import javax.ws.rs.core.UriBuilder;
     
    import com.sun.jersey.api.client.Client;
    import com.sun.jersey.api.client.ClientResponse;
    import com.sun.jersey.api.client.WebResource;
    import com.sun.jersey.api.client.config.ClientConfig;
    import com.sun.jersey.api.client.config.DefaultClientConfig;
     
    public class ClientRequest {
      public static void main(String[] args) {
        String HELLO_REST_URI = "http://localhost:8080/rest";
        ClientConfig config = new DefaultClientConfig();
        Client client = Client.create(config);  
     
        WebResource service = client.resource(UriBuilder.fromUri(HELLO_REST_URI).build());
     
        // Print service status
        System.out.println(service.path("hello").accept(MediaType.TEXT_PLAIN).get(ClientResponse.class).toString());
        // Print response as plain text
        System.out.println(service.path("hello").accept(MediaType.TEXT_PLAIN).get(String.class));
        // Print response as HTML
        System.out.println(service.path("hello").accept(MediaType.TEXT_HTML).get(String.class));
     
      }
    }
  5. Select Run→Run As→Java Application.
  6. In the console, you'll get:

    GET http://localhost:8080/rest/hello returned a response status of 200 OK
    Hello world!
    <html> <title>Hello world!</title><body><h1>Hello world!</body></h1></html> 
teaching_assistant/web_services/jersey_client.txt · Last modified: 2021/09/06 12:50 by Nour
Back to top
CC Attribution-Share Alike 4.0 International
chimeric.de = chi`s home Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0