cap*_*ica 6 java json web-services jax-rs rotten-tomatoes
我想使用烂番茄API搜索电影.
我有一个使用TMDB而不是烂番茄的等效的完全工作的应用程序.
我使用JBoss RESTEasy提供的标准JAX-RS客户端和RESTEasy Jackson2提供程序(我当然不能发布我的API密钥):
public MovieSearchResults search(String query) {
return client
.target("http://api.rottentomatoes.com/api/public/v1.0/movies.json")
.queryParam("apikey", API_KEY)
.queryParam("q", query)
.request(MediaType.APPLICATION_JSON)
.get(MovieSearchResults.class);
}
Run Code Online (Sandbox Code Playgroud)
MovieSearchResults类只是一个用于绑定JSON的JAXB注释类.
直接的问题是Rotten Tomatoes API正在为其所有JSON响应返回内容类型为"text/javascript"的响应.他们表现出不愿意改变他们的服务,即使这显然是在返回JSON时设置的错误内容类型,所以现在它就是它的本质.
我调用服务时遇到的异常是:
Exception in thread "main"
javax.ws.rs.client.ResponseProcessingException:
javax.ws.rs.ProcessingException:
Unable to find a MessageBodyReader of
content-type text/javascript;charset=ISO-8859-1 and type class MovieSearchResults
Run Code Online (Sandbox Code Playgroud)
所以问题是:是否有一种简单的方法来获取/配置标准JAX-RS客户端以将返回的"text/javascript"内容类型识别为"application/json"?
答案是使用JAX-RS ClientResponseFilter.
请求已更改为注册过滤器:
public MovieSearchResults search(String query) {
return client
.register(JsonContentTypeResponseFilter.class)
.target("http://api.rottentomatoes.com/api/public/v1.0/movies.json")
.queryParam("apikey", API_KEY)
.queryParam("q", query)
.request(MediaType.APPLICATION_JSON)
.get(MovieSearchResults.class);
}
Run Code Online (Sandbox Code Playgroud)
过滤器本身只是替换内容类型标头:
public class JsonContentTypeResponseFilter implements ClientResponseFilter {
@Override
public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException {
List<String> contentType = new ArrayList<>(1);
contentType.add(MediaType.APPLICATION_JSON);
responseContext.getHeaders().put("Content-Type", contentType);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6687 次 |
| 最近记录: |