我正在使用 Jersey 和 Jackson 访问 REST Web 服务,该服务正确返回格式正确的 JSON 数据,但具有响应 header :
Content-Type: text/html; charset=UTF-8
即使我在请求 header 中指定了 Accept: application/json ,结果导致 Jersey 抛出:
org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyReader not found for media type=text/html;charset=UTF-8
我正在使用我的代码很好地使用其他网络服务,但我想知道是否有一种方法可以创建我自己的 MessageBodyReader 来处理不匹配的问题,但是我还没有弄清楚如何正确实现它。我打算要求网络服务的所有者修复不匹配的问题,但我不抱太大希望。
最佳答案
好吧,我基本上按照 Stephen C 的建议来解决这个问题,但我想我应该发布更多细节,以防其他人也有同样的情况。首先,我实际上是从 Jersey 指南的几个部分开始的,特别是这一节:
https://jersey.java.net/documentation/latest/user-guide.html#d0e6825
显然,我正在使用 Jersey 作为 javax.ws.rs.client,并且我正在使用 Genson进行 JSON 反序列化。因此,我实现了以下类来实现 MessageBodyReader:
public class BTCEURTradeMessageBodyReader
implements MessageBodyReader<BTCEURTrades> {
final org.slf4j.Logger logger =
LoggerFactory.getLogger(BTCEURTradeMessageBodyReader.class);
@Override
public boolean isReadable(Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
logger.info("isReadable being checked for: {} and media type: {}", type, mediaType);
return type == BTCEURTrades.class;
}
@Override
public BTCEURTrades readFrom(Class<BTCEURTrades> type, Type genericType,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
throws IOException, WebApplicationException {
logger.info("readFrom being called for: {}", type);
BTCEURTrades btceurTrades;
try {
btceurTrades = new Genson().deserialize(entityStream, type);
} catch(Exception e) {
logger.error("Error processing JSON reponse.", e);
throw new ProcessingException("Error processing JSON reponse.");
}
return btceurTrades;
}
}
创建后,它会向客户端注册,如下所示:
client = ClientBuilder.newClient();
client.register(BTCEURTradeMessageBodyReader.class);
关于java - 如何处理不遵守 Accept : application/json using Jersey and Jackson 的 Web 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36380893/