java JAX-RS jersey 客户端:使用状态码读取响应
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15186315/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JAX-RS jersey Client: Reading the Response with status code
提问by WhoAmI
I am using this code for invoking a jersey JAX-RS service using a jersey client.
我正在使用此代码使用 jersey 客户端调用 jersey JAX-RS 服务。
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.
当响应状态代码为 200 时,此代码工作正常。但对于 200 以外的任何其他内容,此代码将引发异常。
How to modify this code so that based on the status code of the response it performs some action?
如何修改此代码,以便根据响应的状态代码执行某些操作?
回答by Ryan Stewart
Use .get(ClientResponse.class)
instead of .get(String.class)
. That suppresses the "exception on bad status" behavior, and the ClientResponsegives you access to details about the HTTP response. The behavior is briefly described in the user guide under "Receiving a response".
使用.get(ClientResponse.class)
代替.get(String.class)
。这会抑制“状态不佳的异常”行为,并且ClientResponse使您可以访问有关 HTTP 响应的详细信息。该行为在“接收响应”下的用户指南中进行了简要描述。