gpt4 book ai didi

java - 使用 JSON 对象数组执行 Post 时出现 MessageBodyProviderNotFoundException

转载 作者:行者123 更新时间:2023-11-29 03:29:25 25 4
gpt4 key购买 nike

我正在创建我的第一个网络服务,所以我可能遗漏了一些非常简单的东西。我在没有 Maven 的 Tomcat 上使用 Jersey 2.x 在 Eclipse Kepler 中创建了一个 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”: enter image description here

我怀疑问题在于它无法将 JSON 转换为我的 POJO 对象,因此我在我的 web.xml 中放置了一个初始化参数,但它没有任何效果。此外,我尝试只发送一个 FilterOption 对象,认为 ArrayList 太复杂,但同样没有效果。

感谢您的宝贵时间:)

最佳答案

我找到了一种避免预期解决方案的方法。我只是使用字符串并使用 gson 库解析它们:

@POST
// @Consumes(MediaType.APPLICATION_JSON)
// @Produces(MediaType.APPLICATION_JSON)
public String getFilteredPictures(String jsonFilters)
{
PictureProvider provider = new PictureProvider();
ArrayList<PictureInfo> pictures = null;
ArrayList<FilterOption> filters = null;
if (jsonFilters != null)
{
Type collectionType = new TypeToken<ArrayList<FilterOption>>()
{}.getType();
filters = gson.fromJson(jsonFilters, collectionType);
}
.....

关于java - 使用 JSON 对象数组执行 Post 时出现 MessageBodyProviderNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19162542/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com