使用 JAX-RS Jersey 2.2 获取带有 Content-Type 和 Accept 标头的请求Jersey、RS、JAX、Accept

2023-09-06 11:31:29 作者:天际征鸿

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:

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);
DNF职业联赛 败者组决赛,59痛失比赛

As you see I am using Jersey 2.2 and I'm still getting a 415 Unsupported Media Type.

EDIT

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

解决方案

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.

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.

Edit

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.

You never specify the content type of your request. Since the server expects a Content-Type header, it responds with 415.