简体   繁体   中英

Access HTTP response when using Jersey client proxy

I'm using Jersey 2.22 to consume a REST api. The approach is contract-first, a service interface and wrappers are used to call the REST api (using org.glassfish.jersey.client.proxy package).

WebClient webClient = ClientBuilder.newClient();
WebTarget webTarget = webClient.getWebTarget(endPoint);
ServiceClass proxy = WebResourceFactory.newResource(ServiceClass.class, webTarget);

Object returnedObject = proxy.serviceMethod("id1");

The question is: how to get the underlying HTTP response (HTTP status + body)?
When the returnedObject is null, I need to analyze the response to get error message returned for example. Is there a way to do it?
I saw that we can plug filters and interceptors to catch the response, but that's not exactly what I need.

You should return Response as the result of the interface method instead of the plain DTO.

I'm not sure about the level of control you're expecting (considering your reply to @peeskillet comment), but the Response object will give you the opportunity to fine tune your server's response (headers, cookies, status etc.) and read all of them at the client side - as you might see taking a look at Response's members like getStatus() and getHeaders() .

The only gotcha here is how to get the body. For this, I'd tell you to use readEntity(Class<T>) (not the getEntity() method as one might try at first). As long as you have the right media type provider registered, you can extract the entity as your DTO class in a easy way.

For example, if you are using maven, jersey and JSON as media type, you can add the following dependency (and take the provider's registration for granted):

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
</dependency>

Then, get the entity body deserialized using:

Response resp = proxy.serviceMethod("id1");
int status = resp.getStatus();
String statusText = resp.getStatusInfo();
String someHeader = resp.getHeaderString("SOME-HEADER");
YourCustomDTO obj = resp.readEntity(YourCustomDTO.class);

When querying a list of your custom objects (ie method returns a JSON array) use the array type to read the body.

Response resp = proxy.serviceMethodThatReturnsCollection();
YourCustomDTO[] obj = resp.readEntity(YourCustomDTO[].class);

Please notice that after reading the body, the stream is closed and trying getEntity() may throw an exception.

Hope it helps.

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