問題
RestTemplateを介して他のAPIを呼び出す必要がありますが、レスポンスに401エラーが発生した場合に追加の設定がない限り、次のように戻ります。
...
org.springframework.web.client.HttpClientErrorException$Unauthorized: 401 : [no body]
...
問題は401エラーの中にno bodyでデータがないことです。
実際に通信ログ確認をすると、 response bodyにエラーコードとエラーメッセージを送るにもかかわらず、RestTemplate 使用時に 401 エラーが発生すると何も受け取れないのです。そのため、エラー内容の詳細が分からず、非常に不便です。
解決策
解決策として、 HttpComponentsClientHttpRequestFactory を実装して restTemplate に設定すればよいです。
設定する方法は次のとおりです。
...
RestTemplate restTemplate = new RestTemplate();
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
...
設定前と後を比較すると次のようになります。
設定前
responseBodyは空です。

設定後
responseBodyの内容を取れました。


少し深掘り
RestTemplate実際の通信はClientHttpRequestFactoryに任せます。デフォルトでは、SimpleClientHttpRequestFactoryを使ってコンストラクタし、java.netのAPIを利用してリクエストを投げます。401レスポンスする際、bodyを取得できないのはjava.netの問題ですね。
コメント