RestTemplate中headers中添加Host不生效

在使用restTemplate访问内网接口时,不打算指host,支持ip访问,所以我们需要再header中指定host.但经调试,发现HttpURLConnection中Host无法覆盖.
解决方案:

Object requestBody = ImmutableMap.of("username", username, "password", password);
HttpEntity request = requestWithHeader(requestBody, headers -> {
headers.add(HttpHeaders.HOST,DEFAULT_API_ACCOUNT_DOMAIN);
headers.add(HttpHeaders.CONTENT_TYPE,MediaType.APPLICATION_JSON_VALUE);
});

//重写HttpURLConnection的headers属性Host,否则自定义添加Host无法覆盖.
System.setProperty("sun.net.http.allowRestrictedHeaders", "true");

 

https://stackoverflow.com/questions/43223261/setting-host-header-for-spring-resttemplate-doesnt-work
 
https://stackoverflow.com/questions/7648872/can-i-override-the-host-header-where-using-javas-httpurlconnection-class 
 
https://stackoverflow.com/questions/9096987/how-to-overwrite-http-header-host-in-a-httpurlconnection
 
 
 
posted @ 2021-05-20 22:52  牧之丨  阅读(709)  评论(0编辑  收藏  举报