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");