Java客户端HttpClient和HttpURLConnection修改请求头Host问题

Method里有method.setRequestHeader(headerName, headerValue)方法,但是没有效果,服务端收到的Host还是IP,跟踪下源码,发现这样写可以生效

      GetMethod method = new GetMethod(url);

      method.getParams().setVirtualHost("google.org");

if(header_user_agent!=null)

method.setRequestHeader("User-agent", header_user_agent);

if(header_referer!=null)

method.setRequestHeader("Referer", header_referer);

/**

* 设置代理服务

* @param httpClient

*/

public static void httpClientProxy(HttpClient httpClient){

String proxy_host = Config.get().get("proxy_host");

int proxy_port = Config.get().getInt("proxy_port", 8080);

String proxy_user = Config.get().get("proxy_user");

String proxy_password = Config.get().get("proxy_password");

String proxy_domain = Config.get().get("proxy_domain");

if(proxy_host!=null){

httpClient.getHostConfiguration().setProxy(proxy_host, proxy_port);

}

if(proxy_user!=null && proxy_password!=null){

//使用抢先认证

httpClient.getParams().setAuthenticationPreemptive(true);

httpClient.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxy_user,proxy_password));

//NT认证代理

if(proxy_domain!=null)

httpClient.getState().setProxyCredentials(AuthScope.ANY,new NTCredentials(proxy_user, proxy_password, "", ""));

}

}

HttpURLConnection还在研究中,先去找下sun.net.www.protocol.http的源码

..............终于在这里找到了http://download.java.net/jdk6/source/

看了sun.net.www.protocol.http.HttpURLConnection

可以这样写

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

  conn = (HttpURLConnection) new URL(url).openConnection();

  conn.setRequestProperty( "User-agent", "Mozilla/9.0 (compatible; MSIE 10.0; Windows NT 8.1; .NET CLR 2.0.50727)" );

  conn.setRequestProperty("Host", "google.org");