简体   繁体   English

Jersey 2 - 从资源方法返回客户端的响应

[英]Jersey 2 - return Client's Response from resource method

I built a reverse proxy (P) to an upstream server (U).我为上游服务器 (U) 构建了一个反向代理 (P)。 A client application (C) will issue a request to P, which will in turn issue a request to U, and the result returned by U should be returned to the client C by proxy P.客户端应用程序(C)将向 P 发出请求,P 又将向 U 发出请求,而 U 返回的结果应通过代理 P 返回给客户端 C。

When I write the code in P like this (I want the proxy to be as generic as possible, and support multiple result types):当我像这样在 P 中编写代码时(我希望代理尽可能通用,并支持多种结果类型):

Client client = // get the client
Invocation.Builder builder = // configure the call to U
return builder.get(InputStream.class);

it works for both JSON and binary data, the result is returned, but the Content-Type header is always set to application/octet-stream , which is wrong.它适用于 JSON 和二进制数据,返回结果,但Content-Type标头始终设置为application/octet-stream ,这是错误的。 I could check the result from U for the type and set it to in the response from my proxy P, but then I would have to mess around with error handling etc. whereas when I just return the InputStream and an error occurs, the builder.get() method throws an exception which is then propagated to the client.我可以检查来自 U 的类型的结果并将其设置为来自我的代理 P 的响应,但随后我将不得不处理错误处理等,而当我只返回 InputStream 并发生错误时, builder.get()方法抛出一个异常,然后将其传播到客户端。

I would actually like to just take the Response returned by U and use it as the return value of P, like this:我实际上只想将 U 返回的 Response 用作 P 的返回值,如下所示:

Client client = // get the client
Invocation.Builder builder = // configure the call to U
return builder.get(); // returns Response

the client C, in my case a Python 3 requests application, get the following error:客户端 C,在我的例子中是 Python 3 requests应用程序,收到以下错误:

requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',))

I tried the following code:我尝试了以下代码:

Response upstreamResponse = client./* code code */.get();
upstreamResponse.bufferEntity();
return Response.fromResponse(upstreamResponse);

but, alas, the result is the same.但是,唉,结果是一样的。

What am I missing?我错过了什么?

I would have expected the proxy to pass the content type through (and maybe other things like content-length and status).我本来希望代理通过内容类型(可能还有其他内容,如内容长度和状态)。 So it would look a bit more like:所以它看起来更像:

Response upstreamResponse = client./* code code */.get();
upstreamResponse.bufferEntity();
return Response.status(upstreamResponse.status())
               .type(upstreamResponse.getMediaType()
                // and so on

Realistically, you may or may not want many of the things from the upstreamResponse header too - what about Cookies for example?实际上,您可能也可能不想要来自 upstreamResponse 标头的许多东西 - 例如 Cookies 呢?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM