简体   繁体   中英

JAX-RS jersey Client: Reading the Response with status code

I am using this code for invoking a jersey JAX-RS service using a jersey client.

public static void main(String[] args) {
    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);

    WebResource service = client.resource(getBaseURI());

    String msg = service.path("rest").path("ExceptionDemo").path("user").queryParam("id", "001").get(String.class);     
    System.out.println(msg);

}

private static URI getBaseURI() {
    return UriBuilder.fromUri("http://localhost:8045/ExceptionHanlding").build();
}

This code works fine when the Response status code is 200. But for anything other than 200, this code throws an exception.

How to modify this code so that based on the status code of the response it performs some action?

Use .get(ClientResponse.class) instead of .get(String.class) . That suppresses the "exception on bad status" behavior, and the ClientResponse gives you access to details about the HTTP response. The behavior is briefly described in the user guide under "Receiving a response" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM