从 ClientResource 检索响应正文

Retrieve response body from ClientResource

我尝试使用 ClientResource 发出 POST 请求,我能够检索响应 STATUS,我也想得到异常时的response body

这是我的代码:

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

这是我的服务器资源 returns 失败时

的代码
getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN);
JsonRepresentation response = new JsonRepresentation( (new JSONObject()).
        put("result", "failed to execute") );
return response;

我尝试抓住 "result" 但没有成功

其实getResponseEntity方法returns响应的内容。它对应于一个表示。如果你希望有一些 JSON 内容,你可以用 JsonRepresentation class 包装它:

try {
    (...)
} catch(ResourceException ex) {
    Representation responseRepresentation
           = clientResource.getResponseEntity();
    JsonRepresentation jsonRepr
           = new JsonRepresentation(responseRepresentation);
    JSONObject errors = jsonRepr.getJsonObject();
}

您可以注意到 Restlet 还支持带注释的异常。

否则我写了一篇关于这个主题的博客post:http://restlet.com/blog/2015/12/21/exception-handling-with-restlet-framework/。我认为它可以帮助你。

蒂埃里