带有Content-Type的GET Request和带有JAX-RS Jersey 2.2的Accept标头 [英] GET Request with Content-Type and Accept header with JAX-RS Jersey 2.2
问题描述
我尝试访问一个开放数据网络服务,该服务为我提供了交通信息.文档说,请求必须为GET
,并且必须包含Accept: application/json
和Content-Type: application/json
.我不明白为什么他们需要Content-Type
,但可以:
I try to access an open data web service which gives me traffic infos. Documentation says that requests have to be GET
and need to contain Accept: application/json
and Content-Type: application/json
. I don't understand why they need the Content-Type
but ok:
我尝试仅使用Accept:
标头来检索数据,但是我总是得到415 Unsupported Media Type
.现在,我目前正在尝试使用这种方式(但是我不确定我是否确实正确设置了两个标头):
I tried to retrieve data with just the Accept:
Header but I'm always getting a 415 Unsupported Media Type
. Now I am currently trying it this way (but I'm not sure if I am really setting both headers correctly):
String entity = ClientBuilder.newClient().target(liveDataURI)
.path(liveDataPath)
.request(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.get(String.class);
如您所见,我正在使用Jersey 2.2,但我仍然得到415 Unsupported Media Type
.
As you see I am using Jersey 2.2 and I'm still getting a 415 Unsupported Media Type
.
编辑
所以我可以使用它,但是我不明白为什么. accept(MediaType.APPLICATION_JSON)
和header("Content-type","application/json")
不一样吗?
So I got it to work but I don't understand why. Isn't accept(MediaType.APPLICATION_JSON)
and header("Content-type","application/json")
the same?
String responseEntity = ClientBuilder.newClient()
.target(liveDataURI)
.path(liveDataPath)
.request(MediaType.APPLICATION_JSON)
.header("Content-type", "application/json")
.get(String.class);
推荐答案
Accept
标头告诉服务器您的客户端在响应中想要什么. Content-Type
标头告诉服务器客户端在请求中发送 的内容.因此,两者不相同.
The Accept
header tells the server what your client wants in the response. The Content-Type
header tells the server what the client sends in the request. So the two are not the same.
如果服务器仅接受application/json
,则必须发送一个指定请求内容的请求:
If the server only accepts application/json
, you must send a request that specifies the request content:
Content-Type: application/json
这就是为什么您编辑的代码可以正常工作的原因.
That's why your edited code works.
修改
In your first code you use WebTarget.request(MediaType... acceptedResponseTypes)
. The parameters of this method
定义接受的响应媒体类型.
define the accepted response media types.
You are using Innvocation.Builder.accept(MediaType... mediaTypes)
on the result of this method call. But accept()
adds no new header, it is unnecessary in your first code.
您永远不会指定请求的内容类型.由于服务器需要一个Content-Type
标头,因此它将以415
进行响应.
You never specify the content type of your request. Since the server expects a Content-Type
header, it responds with 415
.
这篇关于带有Content-Type的GET Request和带有JAX-RS Jersey 2.2的Accept标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!