gpt4 book ai didi

java - 为什么在 restTemplate.exchange 与 httpMethod.POST 之后调用时 HttpStatusCodeException.getResponseBodyAsString() 为空

转载 作者:搜寻专家 更新时间:2023-10-31 08:32:27 24 4
gpt4 key购买 nike

我刚遇到那个问题,不明白为什么会这样。

客户端片段:

try {
ResponseEntity<Credentials> response = this.restTemplate.exchange(uri, HttpMethod.POST, httpEntity,
Credentials.class);
this.userCredentials = response.getBody();
return this.userCredentials;
} catch (HttpStatusCodeException hsce) {
logger.error("loginUser failed with code " + hsce.getMessage());
ObjectMapper mapper = new ObjectMapper();
TransmissionFailureException tfe = new TransmissionFailureException();
try {
if (hsce.getStatusCode() == HttpStatus.UNAUTHORIZED) {
logger.warn(" HIER " + hsce.getMessage());
throw (CredentialsIncorrectException) mapper.readValue(hsce.getResponseBodyAsString(), CredentialsIncorrectException.class);
...

当我将 HttpMethod 设置为 GET(当然也在服务器端)时,hsce.getResponseBodyAsString() 将我的错误的 JSON 表示形式返回为字符串,因为它应该按预期进行,并且解析/映射按预期工作。

奇怪的是,与 SoapUI 执行的完全相同的请求在正文中携带异常,正如 POST 和 GET 上预期的那样。

我是不是哪里弄错了,还是某种错误?

我们将不胜感激。

亲切的问候

编辑:Soap UI 使用 GET 显示的 Json Body:

{
"cause": null,
"stackTrace": [
...
],
"localizedMessage": "No user found with given username...",
"message": "No user found with given username...",
"suppressed": []
}

Soap UI 使用 POST 显示的 Json Body:

{
"cause": null,
"stackTrace": [
...
],
"localizedMessage": "No user found with given username...",
"message": "No user found with given username...",
"suppressed": []
}

StackTrace 太长了,抱歉...

最佳答案

我明白为什么会这样。正如我从文档中看到的那样

"Note: by default the RestTemplate relies on standard JDK facilities to establish HTTP connections. You can switch to use a different HTTP library such as Apache HttpComponents, Netty, and OkHttp through the HttpAccessor.setRequestFactory(org.springframework.http.client.ClientHttpRequestFactory) property."

并查看他们的 doc和警告:

Note that the java.net implementation for HTTP requests may raise an exception when accessing the status of a response that represents an error (e.g. 401). If this is an issue, switch to HttpComponentsClientHttpRequestFactory instead.

所以 java.net impl 在状态码为 401(未授权)时引发异常。

要获取字符串形式的响应主体,只需将请求工厂更改为您的 RestTemplate

    RestTemplate template = new RestTemplate(new HttpComponentsClientHttpRequestFactory());

    template.setRequestFactory(new HttpComponentsClientHttpRequestFactory());

使用 apache http 组件。查看链接 herehere

关于java - 为什么在 restTemplate.exchange 与 httpMethod.POST 之后调用时 HttpStatusCodeException.getResponseBodyAsString() 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33232192/

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