我使用 Apache CXF 提供与 RESTful API 的通信。
我需要使用 PUT 方法通过 API 将一些受约束的实体发送到数据库。
这是提供此方法的正确方式吗?
我问这个问题是因为我收到了 HTTP 500 错误代码响应。
我只能在Apache CXF官方文档中找到GET方法示例;缺少 HTTP PUT、HTTP POST 等。
WebClient client =
WebClient.create("http://MY_SERVER:9090/admission/services/processing");
Admission a = new Admission();
a.setCode("73935282");
:
:
Response r = client.path("/admission").put(a);
// Here I would like to get 201, but there is 500 :(
System.out.println("response: " + r.getStatus());
最佳答案
服务是否需要 XML 以外的内容类型,例如 JSON? WebClient
的默认行为是假设 content-type
为 application/xml
。
这是相关的 source code for WebClient.java :
protected Response doInvoke(String httpMethod, Object body, Class<?> responseClass, Type genericType) {
MultivaluedMap<String, String> headers = getHeaders();
if (body != null) {
if (headers.getFirst(HttpHeaders.CONTENT_TYPE) == null) {
headers.putSingle(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_TYPE.toString());
}
} else {
headers.putSingle(HttpHeaders.CONTENT_TYPE, MediaType.WILDCARD);
}
if (responseClass != null && headers.getFirst(HttpHeaders.ACCEPT) == null) {
headers.putSingle(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML_TYPE.toString());
}
resetResponse();
return doChainedInvocation(httpMethod, headers, body, responseClass, genericType, null, null);
}
如果是这样,您可以使用 type()
在 WebClient
上设置内容类型方法。例如,让客户端生成 JSON:
WebClient client = WebClient.create("http://MY_SERVER:9090/admission/services/processing");
client.type(MediaType.APPLICATION_JSON_TYPE);
Admission a = new Admission();
a.setCode("73935282");
Response r = client.path("/admission").put(a);
关于java - Apache CXF - 以 http 为中心的方法以及从客户端到服务器的 PUT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9976572/