球衣内容类型定制
您好,我有一个场景,我想动态控制球衣 Web 服务返回的内容类型,而不使用请求标头内容类型。
目前我做了标准的事情:
@Produces( {"application/xml", "application/json"})
public ContactsConverter getSearchContacts()
所以默认情况下我会得到 xml。但是,如果我想取回 json 对象,我必须在请求标头中设置“Content-Type: application/json”。目前这对我来说不是一个选择,因为请求来自跨域 ajax 调用,其中内容类型始终为 /。因此,我想在我的请求中使用一个标志或一些巧妙的东西来指定返回的内容类型。我环顾四周,但没有看到任何有用的东西,一个建议是将 json 作为默认值发送,但这是我想避免做的事情。
Hi I've got a scenario where I would like to control the content type return by a jersey web-service dynamically without using request header content-type.
Currently I do the standard thing:
@Produces( {"application/xml", "application/json"})
public ContactsConverter getSearchContacts()
So by default I'll get xml back. However, if I want to get a json object back, i'll have to set "Content-Type: application/json" in my request header. This is currently not an option for me because the request is coming from an cross domain ajax call, where the content-type will always be /. So therefore, I'd like to use a flag in my request or something clever to specify the content-type returned. I've looked around but haven't seen anything helpful, one suggestion is to sent json as the default, but this is something I'd want to avoid doing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,我认为 Jersey 在这里做了错误的事情,因为 Content-Type 是一个描述请求/响应内容的标头,并且您没有在请求中包含任何内容,它实际上应该基于其而是在 Accepts 标头上的行为,但把它放在一边......
仅仅因为它是一个 ajax 调用,并不意味着内容类型将始终是 /,在客户端上您可以像这样调用 setRequestHeader
: -CORS 请求上的类型标头将导致飞行前发生。您必须在服务器代码中支持预检,否则 CORS 请求将被拒绝。为 getSearchContacts 提供常规代码,但预检将通过 OPTIONS 方法进行:
现在将允许带有自定义标头的 CORS 请求。
很容易出错:据我所知,即使是 google 电子表格 api 也无法正确响应预检,这意味着您实际上无法更改 javascript 中的任何数据。
Well first of all, I think that Jersey is doing the wrong thing here, since Content-Type is a header that describes the content of the request/response and you aren't including any content with the request, it should actually be basing its behaviour on the Accepts header instead, but leaving that aside....
Just because it's an ajax call, it doesn't mean that the content-type will always be /, on the client you can call setRequestHeader like so:
Setting the Content-Type header on a CORS request will cause a pre-flight to occur. You have to support the preflight in the server code or the CORS request will be rejected. Provide your normal code for getSearchContacts, but the preflight will come in on with an OPTIONS method:
Now the CORS request with the custom headers will be allowed.
It's easy to get this wrong : as far as I can tell, even the google spreadsheet api doesn't respond correctly to preflights, meaning that you can't actually change any data from javascript.