user1442804
user1442804

Reputation: 43

Jersey converting from ClientResponse to Response

I'm currently using Jersey as a proxy REST api to call another RESTful web service. Some of the calls will be passed to and from with minimal processing in my server.

Is there a way to do this cleanly? I was thinking of using the Jersey Client to make the REST call, then converting the ClientResponse into a Response. Is this possible or is there a better way to do this?

Some example code:

@GET
@Path("/groups/{ownerID}")
@Produces("application/xml")
public String getDomainGroups(@PathParam("ownerID") String ownerID) {
    WebResource r = client.resource(URL_BASE + "/" + URL_GET_GROUPS + "/" + ownerID);
    String resp = r.get(String.class);
    return resp;
}

This works if the response is always a success, but if there's a 404 on the other server, I'd have to check the response code. In other words, is there clean way to just return the response I got?

Upvotes: 4

Views: 18447

Answers (2)

theme
theme

Reputation: 361

for me answer from Martin throw: JsonMappingException: No serializer found for class sun.net.www.protocol.http.HttpURLConnection$HttpInputStream Change from

rb.entity(r.getEntityInputStream());

to

rb.entity(r.getEntity(new GenericType<String>(){}));

helped.

Upvotes: 2

Martin Matula
Martin Matula

Reputation: 7989

There is no convenience method as far as I am aware. You can do this:

public Response getDomainGroups(@PathParam("ownerID") String ownerID) {
    WebResource r = client.resource(URL_BASE + "/" + URL_GET_GROUPS + "/" + ownerID);
    ClientResponse resp = r.get(ClientResponse.class);
    return clientResponseToResponse(resp);
}

public static Response clientResponseToResponse(ClientResponse r) {
    // copy the status code
    ResponseBuilder rb = Response.status(r.getStatus());
    // copy all the headers
    for (Entry<String, List<String>> entry : r.getHeaders().entrySet()) {
        for (String value : entry.getValue()) {
            rb.header(entry.getKey(), value);
        }
    }
    // copy the entity
    rb.entity(r.getEntityInputStream());
    // return the response
    return rb.build();
}

Upvotes: 8

Related Questions