httpClient
网络爬虫就是用程序帮助我们访问网络上的资源,我们一直以来都是使用HTTP协议访问互联网的网页,网络爬虫需要编写程序,在这里使用同样的 HTTP协议访问网页。
加入依赖:
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency>
配置log4j.properties文件
log4j.rootLogger = DEBUG,A1 log4j.logger.org.example01 = DEBUG 1og4j.appender.A1 = org.apache.log4j.ConsoleAppender log4j.appender.A1.layout = org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss,SSS) [%c] [%c]-[%p] %m%n
以GET请求显示爬虫步骤:
public static void main( String[] args ) {
//1.创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//2.输入网址,发起get请求创建HttpGet对象
HttpGet httpGet = new HttpGet("http://baojia.steelcn.cn/");
//3.使用httpClient对象发起请求
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpGet);
//4.解析相应,获取数据
//判断状态码是否相应
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity httpEntity = response.getEntity();
String content = EntityUtils.toString(httpEntity, "utf-8");
System.out.println(content.length());
}
} catch (IOException e) {
e.printStackTrace();
}finally {
// 关闭释放资源
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
//关闭浏览器
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
URL是http协议显示
带get带参请求:
//设置请求地址是:http://www.itcast.com/search?keys=java //创建URIBuilder URIBuilder uriBuilder = new URIBuilder("http://www.itcast.com/search?keys=java"); //设置参数 uriBuilder.setParameter("keys","java"); //2.输入网址,发起get请求创建HttpGet对象 HttpGet httpGet = new HttpGet(uriBuilder.build()); System.out.println("发起请求的信息"+httpGet);
多个参数是可以继续uriBuilder.setParameter("keys","java").setParameter(param,value)
对与pose请求与get类似
设置爬虫参数:连接时间,传输时间
//配置请求信息 RequestConfig config = RequestConfig.custom().setConnectTimeout(1000)//创建链接的最长时间,单位是毫秒 .setConnectionRequestTimeout(500)//设置获取链接的最长时间,单位毫秒 .setSocketTimeout(10 * 1000)//设置数据传输最长时间,单位毫秒 .build(); //给请求设置请求信息 httpGet.setConfig(config);

浙公网安备 33010602011771号