Why does the Default Spring web implementation populate the response in the Body for 401 Unauthorized GET requests? Why does it not set the response Body for POST , PUT 401 responses?
Consider this simple scenario: (PS: Please feel free to modify request type to GET as well.)
Server:
@RestController
@RequestMapping("/v1")
public class TestController {
@PostMapping("/unauth") // You can change this to GET as well which Sets the Content-Length header
public ResponseEntity unAuthTest() {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Some body I'm Expecting");
}
}
Client:
try {
restTemplate.exchange("https://xxxx.com/v1/unauth", HttpMethod.POST, entity, String.class);
} catch (HttpClientErrorException e) {
System.out.println("Response with body content:");
System.out.printf("%s returned a %s status - %s\n", "xxx client", e.getStatusCode(),e.getMessage());
}
I expect a Response:
Response with body content:
xxx client returned a 401 UNAUTHORIZED status - Some body I'm Expecting
But the response was:
Response with body content:
xxx client returned a 401 UNAUTHORIZED status - [no body]
Comment From: knoobie
See https://github.com/spring-projects/spring-framework/issues/14004.
Comment From: philwebb
Thanks for the link @knoobie.
@thekinggpin This is a restriction of the java.net implementation. We have an open issue to make it easier to switch to different implementations. We're also considering using JdkClientHttpRequestFactory as our default.
For now, if you want the message you'll need to inject a RestTemplateBuilder and do something like this:
RestTemplate restTemplate = builder.requestFactory(JdkClientHttpRequestFactory.class).build();
Comment From: philwebb
I've raised https://github.com/spring-projects/spring-framework/issues/32641 to see if we can improve the Spring Framework docs.