【发布时间】:2015-01-07 21:44:27
【问题描述】:
我正在使用来自 tomEE plus 1.7.1 的 Apache CXF WebClient。 (cxf-rt-frontend-jaxrs-2.6.14.jar)
我实现了一个需要 JSON 服务器响应的 REST 客户端:
public RestClient(String aBaseUrl, String aPath) {
this.client = WebClient.create(aBaseUrl);
this.client.path(aPath);
this.client.accept(MediaType.APPLICATION_JSON);
}
public JSONObject post(MultivaluedMap<String, String> params) {
LOG.debug("sending POST request to: " + this.client.getCurrentURI());
LOG.debug("POST parameters: " + PrivacyFilter.getLogLineFor(params));
Form theForm = new Form(params);
JSONObject theJson;
String resp = this.client.post(theForm, String.class);
try {
theJson = new JSONObject(resp);
} catch (JSONException e) {
LOG.warn("got malformed answer from Server - cannot parse as JSON");
LOG.trace(resp);
throw new RuntimeException("got malformed answer from Server - cannot parse as JSON", e);
}
return theJson;
}
我希望服务器在 HTTP 正文中返回 JSON 数据。 我希望所有 HTTP 状态代码都这样。也适用于代码不是 2xx 的错误情况。
这是我的问题。 如果 HTTP 状态代码 >= 400,CXF 接缝(出于任何原因???)抛出 ServerWebApplicationException。我在 WebClient 实现中找到了这段代码:
if (r.getStatus() >= 400 && responseClass != Response.class) {
throw new ServerWebApplicationException(r);
}
这是什么原因? RESTful API 也使用大于 400 的代码来回答不是很正常吗?在我看来,在这种情况下,异常不接缝确实是一个很好的解决方案。
我不知道如何使用 CXF 实现我的 REST 客户端。有没有可能改变这种行为?只有在 responseClass != Response.class 时才会抛出异常接缝。我用这种方式修改了 REST 客户端:
public JSONObject post(MultivaluedMap<String, String> params) {
LOG.debug("sending POST request to: " + this.client.getCurrentURI());
LOG.debug("POST paramters: " + PrivacyFilter.getLogLineFor(params));
Form theForm = new Form(params);
JSONObject theJson;
Response respObject = this.client.post(theForm, Response.class);
// HOW TO GET THE HTTP BODY OUT OF reps?!
try {
theJson = new JSONObject(resp);
} catch (JSONException e) {
LOG.warn("got malformed answer from Server - cannot parse as JSON");
LOG.trace(resp);
throw new RuntimeException("got malformed answer from Server - cannot parse as JSON", e);
}
return theJson;
}
在这里我没有找到访问 HTTP 正文的可能性。 Response 对象没有接缝来拥有它的访问器。 javax.ws.rs.core.Response 中一种有趣的方法是:
Object getEntity()
如果我调用它,我会得到一个 sun.net.www.protocol.http.HttpURLConnection$HttpInputStream 的实例,这并没有什么帮助。
您知道如何使用 CXF 实现 REST 客户端,在 HTTP 状态代码大于 400 的情况下不会崩溃?
【问题讨论】: