我正在尝试使用 CXF 3.1.2 创建休息服务和客户端,如下所示,
服务方法声明:
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes({"application/xml", MediaType.TEXT_PLAIN})
@Path("/agentLogout")
public JSONObject agentLogout(String ext) {
JSONObject obj = new JSONObject();//org.json.simple.JSONObject
obj.put("DN", ext);
return obj;
}
客户端代码:
WebClient client = WebClient.create(REST_URI); // REST_URI is configured correctly
client.path("agentLogout").accept(MediaType.TEXT_PLAIN);
Response agentLogoutResponse = client.post("10245");
System.out.println(agentLogoutResponse.readEntity(JSONObject.class));//org.json.simple.JSONObject
当我运行客户端代码时,我收到以下异常,
在服务端:
Nov 05, 2015 3:07:08 PM org.apache.cxf.jaxrs.impl.WebApplicationExceptionMapper toResponse
WARNING: javax.ws.rs.ClientErrorException: HTTP 406 Not Acceptable
在客户端:
Nov 05, 2015 3:07:08 PM org.apache.cxf.jaxrs.utils.JAXRSUtils logMessageHandlerProblem
SEVERE: No message body reader has been found for class org.json.simple.JSONObject, ContentType: */*
Exception in thread "main" javax.ws.rs.client.ResponseProcessingException: No message body reader has been found for class org.json.simple.JSONObject, ContentType: */*
您能在这里纠正我吗?我也知道在 CXF Rest Web 服务中使用 Json 的正确方法
最佳答案
您的 WS 生成 MediaType.APPLICATION_JSON
:
@Produces(MediaType.APPLICATION_JSON)
您的客户期望 MediaType.TEXT_PLAIN
:
client.accept(MediaType.TEXT_PLAIN);
这就是“HTTP 406 Not Acceptable”的原因。
更改您的客户端以接受 JSON 或更改您的服务器以生成文本。
<小时/>此外,您不需要返回 JSONObject
从你的方法。只需返回一个模型对象。
返回 JSONObject
会使事情变得复杂,因为它将返回 JSONObject
的 JSON 表示形式它不等同于 JSONObject
中包含的对象的 JSON 表示形式.
并且您可能会收到错误“没有找到类 org.json.simple.JSONObject 的消息正文阅读器”,因为 CXF 不知道如何表示 JSONObject
JSON 格式。
在您的情况下,您可以返回 Map<String,String>
包含一项:键 = "DN",值 = "3254"。
关于java - 无法使用 org.json.simple.JSONObject 访问其余 CXF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33541165/