Jersey:如果真正的"物理"响应头没有任何关于它的信息,如何将MediaType设置为javax.ws.rs.core.Response

Ser*_*gey 2 java rest jax-rs jersey http-headers

当我向服务器发送请求时

...
Response response = builder.method(req.getMethod(), Entity.entity(req, req.getMediaType())); // req.getMediaType() return MediaType.APPLICATION_XML
if(response.getStatus() != 200)
   throw new CoreErrorException("core resulted error with status = " + response.getStatus());
T resp = response.readEntity(respType);
...
Run Code Online (Sandbox Code Playgroud)

泽西在最后一行抛出异常:

org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyReader not found for media type=application/octet-stream
Run Code Online (Sandbox Code Playgroud)

我做了一些调查.首先,我抓住了这个回应:

Content-Length: 93
Date: Thu, 21 Nov 2013 12:53:46 GMT
Server: APP

<root>
   <returncode>XXX</returncode>
   <desc>some description</desc>
</root>
Run Code Online (Sandbox Code Playgroud)

标头不包含有关MediaType的任何信息.

实际上,当我尝试调用response.getMediaType()时,它返回null.

我想,那就是问题所在.Jersey无法检测到响应的MediaType并默认设置它("application/octet-stream").但实际上我的回答是XML.有什么方法可以告诉泽西岛吗?

Mic*_*dos 6

尝试Accept通过调用将标头添加到您的请求中WebTarget#request(MediaType),

ClientBuilder.newClient()
    .target("mytarget")
    .request("application/xml")
    .method(req.getMethod(), Entity.entity(req, req.getMediaType()));
Run Code Online (Sandbox Code Playgroud)

服务器是否未Content-Type向响应添加标头.如果不是,您可以尝试使用WriterInterceptor或仅通过调用来更改客户端站点上的标头

Response response = ...;
response.getStringHeaders().putSingle(HttpHeaders.CONTENT_TYPE, "text/plain");
T resp = response.readEntity(respType);
Run Code Online (Sandbox Code Playgroud)