LoginSignup
0
0

More than 3 years have passed since last update.

RestTemplateでHostヘッダが無視される

Posted at

現象

以下のようにRestTemplateにURLのホストとは異なるHostヘッダを指定するとそのヘッダが無視される。

        HttpHeaders headers = new HttpHeaders();
        headers.set("Host", "www.example.com");

        RestTemplate restTemplate = new RestTemplate();

        ResponseEntity<String> responseEntity = restTemplate.exchange(
                "http://httpbin.org/headers", HttpMethod.GET,
                new HttpEntity<String>(null, headers), String.class);

原因

https://stackoverflow.com/questions/43223261/setting-host-header-for-spring-resttemplate-doesnt-work に書いてあるが、RestTemplateの基底実装がHttpUrlConnectionの場合はこの挙動になる。詳しい事はリンク先に書いてあるが、セキュリティ上の理由というかRFC準拠でこうなっている(らしい)

対策

System.setProperty("sun.net.http.allowRestrictedHeaders", "true")

あるいは

-Dsun.net.http.allowRestrictedHeaders=true

もしくは基底実装にApache HttpComponentsを使用する。

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