1 September 2018

JAX-RS 2.0 client example: Client class

public class MyClient {
  public static void main(String[] args) {
    System.out.println("What's the name of this author?: ");
    String authorId = new Scanner(System.in).next();
    
    Client client = ClientBuilder.newClient();
    WebTarget resource = client.target("http://localhost:8080/myrest/webresources");
    Response response = resource
            .path("author")
            .path(authorId)
            .request(MediaType.APPLICATION_JSON)
            .get();

     // historically getStatus returns an int, not a Response.Status
    if (response.getStatus() == Response.Status.OK.getStatusCode()) {
      Author author = response.readEntity(Author.class);
      System.out.println("Found author: " + author.getFirstName() + " " + author.getLastName());
    }else{
      String body = response.readEntity(String.class);
      System.out.println("Not correct (" + response.getStatusInfo().getReasonPhrase() + ")\n " +body);
    }
  }
}

No comments:

Post a Comment