【发布时间】:2013-10-03 15:00:12
【问题描述】:
我正在创建我的第一个 Web 服务,所以我可能遗漏了一些非常简单的东西。 我在 Eclipse Kepler 中使用 Jersey 2.x 在 Tomcat 上没有 Maven 创建了一个 Web 服务,它适用于没有参数的“@GET”请求(从浏览器和客户端应用程序测试),但我遇到了“@POST”问题(代码如下)。这实际上是一个过滤条件非常复杂的get请求。
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String getFilteredPictures(ArrayList<FilterOption> filters)
{
PictureProvider provider = new PictureProvider();
ArrayList<PictureInfo> pictures;
try
{
pictures = provider.getPictures(filters);
Gson gson = new Gson();
return gson.toJson(pictures);
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
我创建了一个虚拟客户端,只是为了看看上面的方法是否有效:
HttpClient httpclient = new DefaultHttpClient();
Gson gson = new Gson();
HttpPost request = new HttpPost(SERVICE_URI + picturesServiceEndPoint);
//create dummy data
ArrayList<FilterOption> filters = new ArrayList<>();
ArrayList<String> options = new ArrayList<>();
options.add("Black");
filters.add(new FilterOption("Color", options));
StringEntity postParam = StringEntity(gson.toJson(filters), "UTF-8");
postParam.setContentType("application/json");
request.setEntity(postParam);
request.setHeader("Accept", "application/json");
try
{
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null)
{
//obtain results..
}
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
当我运行客户端时,服务器会抛出以下异常“.MessageBodyProviderNotFoundException: MessageBodyReader not found for media type=application/json”:
我怀疑问题在于它无法将 JSON 转换为我的 POJO 对象,因此我在 web.xml 中放置了一个 init 参数,但它没有效果。另外,我尝试只发送一个FilterOption对象,认为ArrayList太复杂了,但还是没有效果。
感谢您的宝贵时间:)
【问题讨论】:
-
请附上
FilterOption的代码。它有 JAXB 注释吗? -
不,它没有注释。
-
阅读球衣文档第 9 章:[支持通用媒体类型表示][1]
标签: java json rest post jersey-2.0