spring resttemplate 发送http请求设置host无效

问题

发送请求时,在header中添加host参数,但发送的http请求中,header中无此参数,而是真实的host.

解决办法

需在应用启动时添加
添加:System.setProperty("sun.net.http.allowRestrictedHeaders", "true");

探究

spring resttemplate

resttemplate只是对其他的HTTP客户端的封装,其本身并没有实现HTTP相关的基础功能。其底层实现是可以配置切换的。 RestTemplate 支持至少三种HTTP客户端库。

sun.net.www.protocol.http.HttpURLConnection

146       /*
  147        * Restrict setting of request headers through the public api
  148        * consistent with JavaScript XMLHttpRequest2 with a few
  149        * exceptions. Disallowed headers are silently ignored for
  150        * backwards compatibility reasons rather than throwing a
  151        * SecurityException. For example, some applets set the
  152        * Host header since old JREs did not implement HTTP 1.1.
  153        * Additionally, any header starting with Sec- is
  154        * disallowed.
  155        *
  156        * The following headers are allowed for historical reasons:
  157        *
  158        * Accept-Charset, Accept-Encoding, Cookie, Cookie2, Date,
  159        * Referer, TE, User-Agent, headers beginning with Proxy-.
  160        * 161        * The following headers are allowed in a limited form:
  162        *
  163        * Connection: close
  164        *
  165        * See http://www.w3.org/TR/XMLHttpRequest2.
  166        */

  232           allowRestrictedHeaders = ((Boolean)java.security.AccessController.doPrivileged(
  233                   new sun.security.action.GetBooleanAction(
  234                       "sun.net.http.allowRestrictedHeaders"))).booleanValue();
  235           if (!allowRestrictedHeaders) {
  236               restrictedHeaderSet = new HashSet<String>(restrictedHeaders.length);
  237               for (int i=0; i < restrictedHeaders.length; i++) {
  238                   restrictedHeaderSet.add(restrictedHeaders[i].toLowerCase());
  239               }
  240           } else { 241               restrictedHeaderSet = null;
  242           }


Java中System.setProperty()

https://stackoverflow.com/questions/21204334/system-setproperty-and-system-getproperty
https://www.cnblogs.com/chasewade/p/3387390.html

/*
 * 设置指定键对值的系统属性
 * setProperty (String prop, String value);
 *
 * 参数:
 * prop - 系统属性的名称。
 * value - 系统属性的值。 
 *
 * 返回:
 * 系统属性以前的值,如果没有以前的值,则返回 null。
 *
 * 抛出: 
 * SecurityException - 如果安全管理器存在并且其 checkPermission 方法不允许设置指定属性。
 * NullPointerException - 如果 key 或 value 为 null。
 * IllegalArgumentException - 如果 key 为空。
 * 注:这里的system,系统指的是 JRE (runtime)system,不是指 OS。
 *
*/
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容