今天看了几个使用HttpClient设置头部信息的帖子,发现使用的Header都是commons-httpclient包中的:
import org.apache.commons.httpclient.Header;
但是commons-httpclient是一个遗留版本,官方已经不推荐使用,正确的方法是使用httpclient项目的httpcore-x.xxx.jar包中的Header:
import org.apache.http.Header;
发送请求时设置头部:
HttpClient httpClient = new DefaultHttpClient();
//創建一個httpGet方法
HttpGet httpGet = new HttpGet("http://www.cnblogs.com/loveyakamoz/archive/2011/07/21/2113252.html");
//設置httpGet的头部參數信息
httpGet.setHeader("Accept", "Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
httpGet.setHeader("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7");
httpGet.setHeader("Accept-Encoding", "gzip, deflate");
httpGet.setHeader("Accept-Language", "zh-cn,zh;q=0.5");
httpGet.setHeader("Connection", "keep-alive");
httpGet.setHeader("Cookie", "__utma=226521935.73826752.1323672782.1325068020.1328770420.6;");
httpGet.setHeader("Host", "www.cnblogs.com");
httpGet.setHeader("refer", "http://www.baidu.com/s?tn=monline_5_dg&bs=httpclient4+MultiThreadedHttpConnectionManager");
httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2");
Header headers[] = response.getAllHeaders(); int i = 0; while (i < headers.length) { System.out.println(headers[i].getName() + ": " + headers[i].getValue()); i++; }
参考:HttpClient 4.0的使用详解
HttpClient_4 用法 由HttpClient_3 升级到 HttpClient_4 必看