设置请求头信息User-Agent来模拟浏览器。
先来看User-Agent:
当我们向服务器发送请求时,浏览器会将一些头信息附加上,然后发给服务器。
如上图所示头信息(请求头信息 Request Headers)
我们的代码:
package com.zhi.httpClient2; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class Demo { public static void main(String[] args) throws Exception { CloseableHttpClient closeableHttpClient=HttpClients.createDefault(); //1、创建实例 HttpGet httpGet=new HttpGet("http://www.tuicool.com"); //2、创建请求 httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122 Safari/537.36 SE 2.X MetaSr 1.0"); CloseableHttpResponse closeableHttpResponse=closeableHttpClient.execute(httpGet); //3、执行 HttpEntity httpEntity=closeableHttpResponse.getEntity(); //4、获取实体 System.out.println(EntityUtils.toString(httpEntity, "utf-8")); //5、获取网页内容,并且指定编码 closeableHttpResponse.close(); closeableHttpClient.close(); } }
httpGet.setHeader(String key,String value);
参数是键值对的形式