java Jersey 从 ClientResponse 转换为 Response

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10936718/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 03:09:04  来源:igfitidea点击:

Jersey converting from ClientResponse to Response

javajersey

提问by user1442804

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.

我目前使用 Jersey 作为代理 REST api 来调用另一个 RESTful Web 服务。一些调用将在我的服务器中以最少的处理传入和传出。

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?

有没有办法干净地做到这一点?我正在考虑使用 Jersey 客户端进行 REST 调用,然后将 ClientResponse 转换为 Response。这是可能的还是有更好的方法来做到这一点?

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?

如果响应总是成功,这有效,但如果另一台服务器上有 404,我必须检查响应代码。换句话说,有没有干净的方法来返回我得到的响应?

回答by Martin Matula

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();
}

回答by theme

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

对我来说 Martin throw 的回答: JsonMappingException: No serializer found for class sun.net.www.protocol.http.HttpURLConnection$HttpInputStreamChange from

rb.entity(r.getEntityInputStream());

to

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

helped.

有帮助。