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.
So I got it to work but I don't understand why. Isn't
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 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:
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.
You never specify the content type of your request. Since the server expects a
Content-Type header, it responds with