【问题标题】:Retrieve response body from ClientResource从 ClientResource 检索响应正文
【发布时间】:2016-01-04 14:30:46
【问题描述】:

我尝试使用 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;

我试图捕捉“结果”但没有成功

【问题讨论】:

    标签: java restlet


    【解决方案1】:

    其实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/。我认为它可以帮助你。

    蒂埃里

    【讨论】:

    • 它不起作用...我在我的问题中添加了我的服务器资源的描述,请看一下。
    • 你能运行我的代码并告诉我它是否适合你吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-20
    • 1970-01-01
    • 2019-07-07
    • 1970-01-01
    • 2017-05-09
    • 1970-01-01
    相关资源
    最近更新 更多