1 September 2018

JAX-RS 2.0 client example: Client class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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