我正在创建我的第一个 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 太复杂了,但还是没有效果。
感谢您的时间:)