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.client.Client;
    import javax.ws.rs.client.ClientBuilder;
    import javax.ws.rs.client.WebTarget;
    import javax.ws.rs.core.MediaType;
    import javax.ws.rs.core.Response;
    import javax.ws.rs.core.UriBuilder;
     
    import org.glassfish.jersey.client.ClientConfig;
     
    public class ClientRequest {
      public static void main(String[] args) {
        String HELLO_REST_URI = "http://localhost:8080/rest";
        ClientConfig config = new ClientConfig();
        Client client = ClientBuilder.newClient(config); 
     
        WebTarget target = client.target(UriBuilder.fromUri(HELLO_REST_URI)).path("hello");
     
        // Print service status
       //System.out.println(target.request(MediaType.TEXT_PLAIN).get().getStatus());
        String response = target.request().accept(MediaType.TEXT_PLAIN).get(Response.class).toString();
        System.out.println(response);
        // Print response as plain text
        System.out.println(target.request().accept(MediaType.TEXT_PLAIN).get(String.class));
        // Print response as HTML
        System.out.println(target.request(MediaType.TEXT_HTML).get(String.class));
     
      }
    }
  5. Select Run→Run As→Java Application.
  6. In the console, you'll get:

    InboundJaxrsResponse{context=ClientResponse{method=GET, uri=http://localhost:8080/rest/hello, status=200, reason=OK}}
    Hello world!
    <html> <title>Hello world!</title><body><h1>Hello world!</body></h1></html>
teaching_assistant/web_services/jersey_client_v234.txt · Last modified: 2021/09/06 13:09 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