使用 JAX-RS Jersey 2.2 获取带有 Content-Type 和 Accept 标头的请求 [英] GET Request with Content-Type and Accept header with JAX-RS Jersey 2.2

查看:27
本文介绍了使用 JAX-RS Jersey 2.2 获取带有 Content-Type 和 Accept 标头的请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于使用 JAX-RS Jersey 2.2 获取带有 Content-Type 和 Accept 标头的请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆