0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【RestTemplate】ステータスコード401でレスポンスボディが入っていない不具合

Posted at

背景

NestJSで発生させた。401のエラーレスポンスをSpring Bootに返却し、RestTemplate上でエラーを返すようにしたかったのですが、なぜかレスポンスボディが入ってこず、対応に時間がかかったので、備忘録として書き記したいと思います。

原因

先に結論を言うと、以下のようにRestTemplateに別のHTTPクライアンライブラリーに切り替えることで、レスポンスボディが入ってくるようになります。

HttpClient httpClient = HttpClientBuilder.create().build();
ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);

ソース:https://stackoverflow.com/questions/17177107/getting-400-bad-request-when-using-spring-resttemplate-to-post

原因は以下にSpring公式に記載のある通り、デフォルトの通りだと(java.netHTTP)だと、エラーを表す応答ステータスにアクセスする際に例外が発生する可能性があるからだそうです。問題に応じて別のHTTPクライアンライブラリーに切り替える必要があるようです。
https://docs.spring.io/spring-framework/docs/current/reference/html/integration.html#rest-resttemplate-create

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?