文章目录:
HttpClient(请求数据):
创建httpclient(介绍两种方式):
方式一:
CloseableHttpClient httpclient = HttpClients.createDefault();
方式二(使用连接池获取httpclient):
//创建连接池管理器
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
//设置最大连接数
cm.setMaxTotal(200);
//设置访问每个网站得最大连接数,不影响其它网站得访问
cm.setDefaultMaxPerRoute(20);
//返回httpclient
return HttpClients.custom().setConnectionManager(cm).build();
生成URI(控制台打印出来可以看到是自动生成?来连接参数):
URIBuilder uriBuilder = new URIBuilder("http://www.baidu.com/s").// 设置参数
setParameter("ie", "utf-8").// 第一个参数
setParameter("f", "8").// 第二个参数
setParameter("wd", "test");// 第三个参数
URI uri = uriBuilder.build();
声明请求方式get/post(传入String类型参数,可以直接放入自己拼接的字符串URL):
HttpGet httpGet = new HttpGet(uri);
HttpPost httpPost = new HttpPost("https://www.xicidaili.com/nn/" + id);
配置请求参数以及代理IP:
// 代理IP设置,代理 ip查询地址:https://www.xicidaili.com/
HttpHost httoHost = new HttpHost("118.181.226.166",44640);
// 配置请求参数
RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(3000).// 3秒,重连接池获取连接最长时间
setConnectTimeout(5000).// 创建连接最长时间
setSocketTimeout(20 * 1000).// 20秒,数据传输最长时间
// setProxy(httoHost).// 设置代理
build();
httpGet.setConfig(config);
设置用户代理信息:
httpGet.setHeader("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18363");
使用httpclient发起请求,判断状态码,并获取数据:
CloseableHttpResponse response = httpclient.execute(httpGet);
// 判断状态码是否为200
if (response.getStatusLine().getStatusCode() == 200) {
// 获取响应数据
HttpEntity entity = response.getEntity();
String string = EntityUtils.toString(entity, "UTF-8");
// 存入本地
FileUtils.writeStringToFile(new File("C:/Users/17210/Desktop/test2.html"), string, "utf-8");
}
response.close();
httpclient.close();
Jsoup解析筛选数据:
注:jsoup也能实现请求,但是不大好使,下面举个例子
//第一个参数为URL类型,第二个应该是超时时间
Document dom = Jsoup.parse(url, timeoutMillis);
用jsoup读取本地html,并获取需要的内容:
注:之所以前面存入本地是为了方便查看返回的html结构,以此来寻找特征筛选需要的内容
方式一(不如方式二好使,看看就行):
String html = FileUtils.readFileToString(new File("C:/Users/17210/Desktop/test.html"), "utf-8");
Document dom = Jsoup.parse(html);
// 通过ID获取具体元素得id
String Idtext = dom.getElementById("foot").id();
// 直接解析dom中得元素,通过标签获取多个元素得文本
String Tagtext = dom.getElementsByTag("title").first().text();
// 通过属性获取多个元素的多个或单个属性值,文本内容,id
Attributes Attrtext = dom.getElementsByAttribute("onclick").first().attributes();//默认取得全部匹配的属性值
String strings = Attrtext.toString();
String Attrtext1 = dom.getElementsByAttributeValue("onclick","return false;").get(2)