1、不废话,上代码:
public static void main(String[] args) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建HttpClient实例
HttpGet httpGet = new HttpGet("http://www.tuicool.com"); // 创建Httpget实例
//设置Http报文头信息
httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0");
HttpHost httoHost = new HttpHost("113.2.63.7",8118);//代理Ip
//RequestConfig requestConfig = RequestConfig.custom().setProxy(httoHost).build();
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(10000)//设置连接超时时间
.setSocketTimeout(10000)//设置读取超时时间
.setProxy(httoHost)//设置代理
.build();
httpGet.setConfig(requestConfig);
CloseableHttpResponse response = null;
response = httpClient.execute(httpGet); // 执行http get请求
HttpEntity httpEntity = response.getEntity(); // 获取返回实体
String web = EntityUtils.toString(httpEntity, "utf-8"); // 解析实体
System.out.println("网页内容是:");
System.out.println(web);
response.close(); // 关闭response
httpClient.close(); // 关闭HttpClient实体
}