Spring Boot 接收POST调用的HttpClientErrorException时缺少ResponseBodyAsString

gblwokeq  于 2023-04-20  发布在  Spring
关注(0)|答案(1)|浏览(117)

我试图在RestClient调用中发送带有Http状态码的自定义错误消息
微服务1代码:

try{
   String method = request.getMethod();
   RestTemplate restTemplate = new RestTemplate();
   ResponseEntity<byte[]> responseEntity = restTemplate.exchange("/someUrl", method, entity, byte[].class);
} catch (HttpServerErrorException | HttpClientErrorException e) {
   String errorString = e.getResponseBodyAsString();
   if(Strings.isNullOrEmpty(errorString)) {
      errorString = e.getMessage();
   }
   return new ResponseEntity<>(errorString, new HttpHeaders(), e.getStatusCode());
}

微服务2代码:

@RequestMapping(value="/someUrl", method= { RequestMethod.GET, RequestMethod.POST})
public ResponseEntity<?> executeSoapServer(@RequestHeader HttpHeaders headers, HttpServletRequest request, HttpServletResponse resp){
  JsonObject obj = new JsonObject();
  obj.addProperty("errorMessage", "test error message")
  return new ResponseEntity<>(obj.toString(), new HttpHeaders(), HttpStatus.UNAUTHORIZED);
}

从微服务1 GET调用响应:响应状态码-401

{
  "errorMessage": "test error message"
}

从微服务1 POST调用响应:响应状态码-401

401 null

对于GET方法,它按预期工作,但对于POST/PUT/DELETE,它不适用于微服务到微服务。
当我使用POST方法直接从postman中点击微服务2时,它可以工作,但是当我使用POST方法从微服务1中点击微服务2时,它不工作。
当我从微服务1点击微服务2控制器时,下面是响应头:

{
Access-Control-Allow-Credentials=[true], 
Access-Control-Allow-Methods=[GET,POST,PUT,PATCH,DELETE,HEAD], 
X-Application-Context=[eportal:local:8082], 
ep-flowid=[c35c3098-a7a5-712a-8e38-4d1ad99fccd0], 
Access-Control-Expose-Headers=[ep-flowid], 
X-Content-Type-Options=[nosniff], 
X-XSS-Protection=[1; mode=block], 
Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], 
Pragma=[no-cache], 
Expires=[0], 
X-Frame-Options=[DENY], 
Content-Type=[application/json;charset=UTF-8], 
Content-Length=[29], 
Date=[Mon, 01 Jun 2020 13:59:59 GMT]
}

当我从Postman点击微服务2控制器时,下面是响应头:

nhaq1z21

nhaq1z211#

+1
我也有同样的经历。解决办法?

相关问题