Directorio de artículos
El rastreador web es un programa o script que rastrea automáticamente la información de la World Wide Web de acuerdo con ciertas reglas. Siempre hemos utilizado el protocolo HTTP para acceder a páginas web en Internet, y los rastreadores web necesitan escribir programas, donde se utiliza el mismo protocolo HTTP para acceder a las páginas web. Aquí utilizamos la tecnología del cliente de protocolo HTTP de Java HttpClient para capturar datos de páginas web.
Preparación ambiental
Introducir la dependencia de maven
<!-- HttpClient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<!-- 日志 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
</dependency>
Agregar archivo de configuración de registro
log4j.rootLogger=DEBUG,A1
log4j.logger.cn.itcast = DEBUG
log4j.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} [%t] [%c]-[%p] %m%n
http Obtener solicitud
el código se muestra a continuación:
public static void getTest()throws Exception{
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://www.itcast.cn?pava=zhangxm");
CloseableHttpResponse response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(content);
}
}
Solicitud http POST
/**
* java 代码发送post请求并传递参数
* @throws Exception
*/
public static void postTest () throws Exception{
//创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(1000)//设置创建连接的最长时间
.setConnectionRequestTimeout(500)//设置获取连接的最长时间
.setSocketTimeout(10 * 1000)//设置数据传输的最长时间
.build();
//创建HttpGet请求
HttpPost httpPost = new HttpPost("http://www.itcast.cn/");
httpPost.setConfig(requestConfig);
CloseableHttpResponse response = null;
try {
//声明存放参数的List集合
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pava", "zhangxm"));
//创建表单数据Entity
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "UTF-8");
//设置表单Entity到httpPost请求对象中
httpPost.setEntity(formEntity);
//使用HttpClient发起请求
response = httpClient.execute(httpPost);
//判断响应状态码是否为200
if (response.getStatusLine().getStatusCode() == 200) {
//如果为200表示请求成功,获取返回数据
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
//打印数据长度
System.out.println(content);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//释放连接
if (response == null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
httpClient.close();
}
}
}
Grupo de conexiones httpClient
Si tiene que crear HttpClient para cada solicitud, habrá problemas frecuentes de creación y destrucción, puede usar el grupo de conexiones para resolver este problema.
/ **
- Utilice el grupo de conexiones httpClient sin crear un cliente nuevo y destructor cada vez
- @throws IOException
* /
public static void connPoolTest () lanza IOException { PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager (); // 设置 最大 连接 数cm.setMaxTotal (200); // 设置 每个 主机 的 并发 数cm.setDefaultMaxPerRoute (20); para (int i = 0; i <10; i ++) { CloseableHttpClient httpClient = HttpClients.custom (). setConnectionManager (cm) .build (); System.out.println ("httpClient:" + httpClient); httpClient.close (); } }