Jersey 客户端在重定向时忘记接受标头
我正在尝试使用 Jersey 作为 RESTful 应用程序的客户端。具体来说,我想向服务器POST
一些JSON并获取JSON,所以我的代码如下所示:
final JSONObject config = new JSONObject();
clientConfig.put("fooParam", 60 * 5); /* 5 min timeout */
final JSONObject newClient = client.resource(/* URL */).
type(MediaType.APPLICATION_JSON).
accept(MediaType.APPLICATION_JSON).
post(JSONObject.class, config);
这会生成带有Content-Type
的预期HTTP请求,并且适当设置的 Accept
标头。现在,服务器决定创建请求的资源,并使用 HTTP/1.1 303 See Other
响应进行重定向(据我所知,这是一个很好的做法)。好消息是 Jersey 愉快地获取了 Location
标头并确实请求了它被告知的资源。糟糕的是,它似乎忘记了我只想获取 application/json
资源并发送 GET
,
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
服务器愉快地回答(使用完全合法的 HTML) 。我使用 Wireshark 验证了这一点。问题是 Jersey 在此问题上崩溃了,因为它无法将其解析为 JSONObject
。所以我的问题是
- Jersey 的行为是正确的还是错误?
- 有没有一些聪明的方法来解决这个问题?
我知道我可能会浏览 Jersey 的 ClientResponse
类,看看我自己是否被重定向,但我认为应该有更好的方法来做到这一点。
I'm trying to use Jersey as a client for a RESTful application. Specifically I'd like to POST
some JSON to the server and get JSON back, so my code looks like this:
final JSONObject config = new JSONObject();
clientConfig.put("fooParam", 60 * 5); /* 5 min timeout */
final JSONObject newClient = client.resource(/* URL */).
type(MediaType.APPLICATION_JSON).
accept(MediaType.APPLICATION_JSON).
post(JSONObject.class, config);
this generates the expected HTTP request with the Content-Type
and Accept
headers set appropriately. Now the server decides the create the requested resource and redirects there using a HTTP/1.1 303 See Other
response (which is good practice as far as I know). The good news is that Jersey happily picks up the Location
header and indeed requests the resource it was told to. The bad thing is that it seems to have forgot that I only wanted to get application/json
resources and sends a GET
with
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
which the server answers happily (with perfectly legal HTML). I verified this using Wireshark. The problem is that Jersey blows up on this as it can not parse this into a JSONObject
. So my question is
- Is that behaviour of Jersey correct or rather a bug?
- Is there some clever way around this?
I'm aware that I could possibly go through Jersey's ClientResponse
class and see if I was redirected myself, but I think there should be a better way to do this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在与穿着球衣的 Pavel 简短对话之后邮件列表中,问题似乎出在 Java 库中的
HttpURLConnection
类上。通过使用 Apache HTTP 客户端库 绑定泽西岛,效果很好。After a short conversation with Pavel on a Jersey mailing list, it seems as if the problem lies withing the
HttpURLConnection
class from the Java libraries. Working around this is easy by using the Apache HTTP Client library binding for Jersey, which works nicely.