gpt4 book ai didi

java - 从 ClientResource 检索响应正文

转载 作者:行者123 更新时间:2023-11-30 03:06:41 24 4
gpt4 key购买 nike

我尝试使用 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/ 。我认为它可以帮助你。

蒂埃里

关于java - 从 ClientResource 检索响应正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34593408/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com