CXC0 2020-04-25
java爬虫
核心:httpclient slf4j jsoup
slf4j 配置文件log4j.properties
log4j.rootlogger=DEBUG,A1
log4j.logger.cn.itcast = DEBUG
log4j.appender.A1=org.apche.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apche.log4j.patternLayout
log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c] -[%p] %m%n
1,步骤
首先获取CloseableHttpClient 对象(浏览器)
CloseableHttpClient client =HttpClients.createDefault();
获取网址HttpGet /HtppPost
HtppGet get=new HttpGet(url)
通过CloseableHttpClient 发送请求(execute)返回响应对象CloseableHttpResponse
CloseableHttpRespose respose =client.execute(get);
判断状态码。是否请求成功
respose.getStatusLine().getStatusCode()==200 既请求成功
获取响应体 EntityUtils解析
HttpEntity entity=res.getEntity();
EntityUtils.toString(entity,utf8)返回utf8编码的字符串
请求完后关闭response 和httpclient
2、带参数的请求
get请求传参
创建URIBuild对象
URIBuild build=new URIBuild(url)
设置参数
build.setParameter(param,value)
在创建请求对象时 HttpGet get=new HttpGet(build.build()) 即可设置参数
3、post请求传参
采用list集合封装表单中的参数
List<NameValuePair> params=new ArrayList<NmaeValuePair>();
params.add(new BasicNameValuePair(param,value))
创建表单的entity对象
UrlEncodedFromEntity formentity=new UrlEncodeFromEntity(params,utf8)
设置表单的entity到post请求对象中
HttpPost post=new HttpPost(url,formentity)
4、连接池
创建连接池
poolingHttpClientConnectonManager cm=new poolingHttpClientConnectonManager();
获取来连接
CloseableHttpClient httpclient=Httpclients.coutom().setConnectionManager(cm).build();
使用完后不要关闭httpclient
配置请求信息
RequestConfig config =RequestConfig.custom().setConnectionTimeout()//设置连接最长时间
.setConectionRequestTimeout()//设置获取连接最长时间
.setSocketTimeout()//设置数据传输最长时间
.build();//返回RequestConfig对象
通过不同的请求 将RequestConfig 设置进去 :HttpGet.setConfig();