首页 > 解决方案 > 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 错误的响应正文

标签: javaresthttpoauth-2.0

解决方案


您可以在 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;

    }

推荐阅读