[Java爬虫HttpClient_Demo3更换高匿IP并设置超时断连]

项目托管平台: 码云地址:

https://gitee.com/HDMBS/JavaSpiderDemo.git

public static void main(String[] args) throws IOException {
// 模拟出真实的HTTP交互并获取图片,
//Maven_Jar参考Java爬虫Demo2
/*
* 1.设置请求对象 User-Agnet httpGet.setHeader("User-Agent",
* "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0"
* );
* 
* 2.获取响应内容类型 Content-Type HttpEntity entity = respond.getEntity();
* System.out.println(entity.getContentType().getValue());
* 
* 3.获取响应状态码 Status
*
* 200:正常 403:拒绝 500:服务器报错 400:未找到页面
* 
* CloseableHttpResponse respond = httpclient.execute(httpGet);
* System.out.println(respond.getStatusLine().getStatusCode());
*
* 4.复制资源: commons io 2.5 _Jar : 复制网络中的资源
* 
* 5.设置高匿IP 参考网站:http://www.xicidaili.com/nn/ HttpHost proxy=new
* HttpHost("175.155.213.235", 9999); RequestConfig
* config=RequestConfig.custom().setProxy(proxy).build();
* httpGet.setConfig(config);
*
* 6.设置连接超时,自动断连接,不会让程序一直连; RequestConfig config =
* RequestConfig.custom().setConnectTimeout(10000)// 设置连接时间超时10秒
* .setSocketTimeout(1000)// 设置读取时间超时10秒 .build(); httpGet.setConfig(config);


// 访问网址
final String URL = "http://www.xicidaili.com/nn/";


// 创建可关闭的HttpClient实例对象(新版本才可以)相当于创建了一个模拟浏览器
CloseableHttpClient httpclient = HttpClients.createDefault();


// 一般爬虫请求都用Get,Get请求在HTTP请求协议里代表安全的查看:这个请求对象里可以添加http的请求头等
HttpGet httpGet = new HttpGet(URL);


// 设置超时断连


RequestConfig configDL = RequestConfig.custom().setConnectTimeout(1000)// 设置连接时间超时10秒断连
.setSocketTimeout(1000)// 设置读取时间超时10秒断连
.build();


// 设置高匿IP
HttpHost proxy = new HttpHost("112.84.192.174", 8118);
RequestConfig configIP = RequestConfig.custom().setProxy(proxy).build();


// 添加请求配置


httpGet.setConfig(configDL);
httpGet.setConfig(configIP);


// 设置Get请求头的 User-Agent (模拟代理浏览器信息)
httpGet.setHeader("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0");


// 用浏览器模拟对象httpClient,发送一个Get请求:可以通过这个响应对象获得很多http的响应信息
CloseableHttpResponse respond = httpclient.execute(httpGet);


// 获得状态码
System.out.println(respond.getStatusLine().getStatusCode());


// 获取返回的网页实体
HttpEntity entity = respond.getEntity();
if (entity != null) {
// 获取响应内容类型
System.out.println(entity.getContentType().getValue());
}


// 获取网页实体对象转换为字符串,并指定最终编码
String entitystr = EntityUtils.toString(entity, "utf-8");


System.out.println(entitystr);


// 关闭流资源
httpclient.close();
// 关闭流资源
respond.close();


}
发布了29 篇原创文章 · 获赞 9 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_37977176/article/details/78708352