[英]Retrieve response body from ClientResource
我尝试使用ClientResource发出POST请求,我能够检索响应STATUS ,我也想在遇到异常时获取响应正文 。
这是我的代码:
public static Pair<Status, JSONObject> post(String url, JSONObject body) {
ClientResource clientResource = new ClientResource(url);
try {
Representation response = clientResource.post(new JsonRepresentation(body), MediaType.APPLICATION_JSON);
String responseBody = response.getText();
Status responseStatus = clientResource.getStatus();
return new ImmutablePair<>(responseStatus, new JSONObject(responseBody));
} catch (ResourceException e) {
logger.error("failed to issue a POST request. responseStatus=" + clientResource.getStatus().toString(), e);
//TODO - how do I get here the body of the response???
} catch (IOException |JSONException e) {
throw e;
} finally {
clientResource.release();
}
}
这是发生故障时我的服务器资源返回的代码
getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN);
JsonRepresentation response = new JsonRepresentation( (new JSONObject()).
put("result", "failed to execute") );
return response;
我试图抓住“结果”没有成功
实际上, getResponseEntity
方法返回响应的内容。 它对应于一个表示。 如果需要一些JSON内容,可以用JsonRepresentation
类包装它:
try {
(...)
} catch(ResourceException ex) {
Representation responseRepresentation
= clientResource.getResponseEntity();
JsonRepresentation jsonRepr
= new JsonRepresentation(responseRepresentation);
JSONObject errors = jsonRepr.getJsonObject();
}
您会注意到Restlet还支持带注释的异常。
否则,我会写一篇有关此主题的博客文章: http : //restlet.com/blog/2015/12/21/exception-handling-with-restlet-framework/ 。 我认为这可以为您提供帮助。
蒂埃里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.