当我向服务器发送请求时
...
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);
...
Jersey 在最后一行抛出异常:
org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyReader not found for media type=application/octet-stream
我做了一些调查。首先,我收到了回复:
Content-Length: 93
Date: Thu, 21 Nov 2013 12:53:46 GMT
Server: APP
<root>
<returncode>XXX</returncode>
<desc>some description</desc>
</root>
Header 不包含任何有关 MediaType 的信息。
确实,当我尝试调用 response.getMediaType() 时,它返回了 null。
我想,这就是问题所在。 Jersey 无法检测响应的 MediaType 并默认设置它(“application/octet-stream”)。但实际上,我的回复正文是 XML。有什么方法可以告诉 Jersey 这件事吗?
最佳答案
尝试通过调用 WebTarget#request(MediaType)
将 Accept
header 添加到您的请求中,
ClientBuilder.newClient()
.target("mytarget")
.request("application/xml")
.method(req.getMethod(), Entity.entity(req, req.getMediaType()));
服务器是否不在响应中添加Content-Type
header 。如果不是,您可以尝试使用 WriterInterceptor
或简单地通过调用
Response response = ...;
response.getStringHeaders().putSingle(HttpHeaders.CONTENT_TYPE, "text/plain");
T resp = response.readEntity(respType);
关于java - Jersey:如何将 MediaType 设置为 javax.ws.rs.core.Response,如果真实的 "physical"响应 header 没有任何相关信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20124001/