Java 从ClientResource检索响应正文

Java 从ClientResource检索响应正文,java,restlet,Java,Restlet,我尝试使用ClientResource发出POST请求,我能够检索响应状态,我还希望在遇到异常时获取响应正文 这是我的密码: public static Pair<Status, JSONObject> post(String url, JSONObject body) { ClientResource clientResource = new ClientResource(url); try { Representation response = c

我尝试使用ClientResource发出POST请求,我能够检索响应状态,我还希望在遇到异常时获取响应正文

这是我的密码:

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();
    }
}

我试图捕获“result”,但没有成功

事实上,
getResponseEntity
方法返回响应的内容。它对应于一个表示。如果需要一些JSON内容,可以使用
JsonRepresentation
类对其进行包装:

try {
    (...)
} catch(ResourceException ex) {
    Representation responseRepresentation
           = clientResource.getResponseEntity();
    JsonRepresentation jsonRepr
           = new JsonRepresentation(responseRepresentation);
    JSONObject errors = jsonRepr.getJsonObject();
}
您可以注意到,Restlet还支持带注释的异常

否则,我写了一篇关于这个主题的博文:。我想它可以帮助你


Thierry

它不起作用。。。我在问题中添加了我的服务器资源的描述,请看一看。你能运行我的代码并告诉我它是否适合你吗?
try {
    (...)
} catch(ResourceException ex) {
    Representation responseRepresentation
           = clientResource.getResponseEntity();
    JsonRepresentation jsonRepr
           = new JsonRepresentation(responseRepresentation);
    JSONObject errors = jsonRepr.getJsonObject();
}