java - java中响应代码为4xx时如何从REST API解析响应正文
问题描述
我正在尝试使用 OauthClient 访问 REST API
try {
OAuthClient client = new OAuthClient(new URLConnectionClient());
OAuthResourceResponse response = client.resource(request, OAuth.HttpMethod.POST, OAuthResourceResponse.class);
} catch (Exception ex) {
ex.printStackTrace();
throw ex;
}
当我使用 Postman 执行调用时,api 调用返回一个响应体,但是当我使用上面的这段代码时,它会抛出异常并且我看不到响应体,以便对其进行解析。
这是一个例外:
org.apache.oltu.oauth2.common.exception.OAuthSystemException: java.io.IOException: Server returned HTTP response code: 409 for URL:
是否可以解析 4xx 错误的响应正文
解决方案
您可以在 catch 块中构建响应对象并返回
} catch (Exception ex) {
return Response.status(Response.Status.BAD_REQUEST).entity(new PresenterClass(ex.getMessage())).build();
}
使用 Presenter 类构造函数
Public PresenterClass(String errorMessage){
this.message = errorMessage;
}
推荐阅读
- if-statement - 在 SASS 中的 if 语句中使用“每个循环变量”
- r - 电源点损坏使用官员
- c# - 如何在uwp中的ListView的选定项目上显示选中的复选框
- sat - 我正在使用 Sugar(基于 SAT 的约束求解器)进行实验
- python - 使用 Asana api 在 Asana 中创建带有附件的任务
- javascript - 动态添加输入字段值jQuery
- ios - 如何防止iOS应用被暂停
- c++ - std::initializer 列表全局/静态对象的生命周期
- python - 将flask应用程序部署到nginx web服务器后,swagger记录未加载
- node.js - 如何为 API 设置路由