多读多写多记录,多学多练多思考。----------- Banana.Banuit(香柚帮)
//设置代理IP、端口、协议(请分别替换)
HttpHost proxy = new HttpHost("你的代理的IP", 8080, "http");
//把代理设置到请求配置
RequestConfig requestConfig = RequestConfig.custom()
.setProxy(proxy) //设置代理
.setConnectTimeout(120000) //连接时间60s
.setSocketTimeout(120000) //传输时间60s
.build();
//实例化CloseableHttpClient对象
CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
String uri = "http://www.banuit.com";
// 定义请求的参数
//URI uri = new URIBuilder("http://www.banuit.com/s").setParameter("name", "banana").build();
//访问目标地址
HttpGet httpGet = new HttpGet(uri);
//请求返回
CloseableHttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//请求体内容
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
//内容写入文件
FileUtils.writeStringToFile(new File("D:\\dev\\baidu.html"), content, "UTF-8");
System.out.println("内容长度:"+content.length());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpResponse != null) {
httpResponse.close();
}
//相当于关闭浏览器
httpClient.close();
}
已过时的类和方法对比
//3.X
HttpClient client=new DefaultHttpClient();
client.setConnectionTimeout(120000);
client.setTimeout(120000);
//4.X
HttpClient httpClient=new DefaultHttpClient();
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,120000);//连接时间
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,120000);//数据传输时间