球衣客户端获取错误消息正文

jersey client get error message body

我正在使用以下代码来消费休息post服务

Client client = ClientBuilder.newClient();
WebTarget target = client.target("wrong url");
Invocation.Builder builder = target.request(MediaType.APPLICATION_JSON);
Response response = builder.post(Entity.entity(param, MediaType.APPLICATION_JSON), Response.class);

不出所料,我遇到了错误。和状态代码 400 Bad Request。但我没有收到错误消息。当我 运行 response.getStatusInfo() 我收到了错误的请求,但我的服务器发送了额外的信息。

当我使用 postman 调用它时,我在 Body window 中得到错误信息。

那么我如何从响应对象中获取这个错误主体信息呢? 或者其他方式???

您像往常一样通过 Response#readEntity:

获得响应正文

Read the message entity input stream as an instance of specified Java type using a MessageBodyReader that supports mapping the message entity stream onto the requested type.

示例:

Client client = ClientBuilder.newClient();
WebTarget target = client.target("wrong url");
Invocation.Builder builder = target.request(MediaType.APPLICATION_JSON);
Response response = builder.post(Entity.entity(param, MediaType.APPLICATION_JSON), Response.class);
String body = response.readEntity(String.class);

Response#getStatusInfo you get only HTTP status, class and reason phrase.