java爬虫.HttpClient.请求参数

假装没事ソ 提交于 2020-02-07 15:47:27

HttpClient.请求参数

有时候因为网络,或者目标服务器的原因,请求需要更长的时间才能完成,我们需要自定义相关时间

package cn.csdn.crawlar.test;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class HttpConfigTest {

    public static void main(String[] args) {
        //创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        //创建HttpGet对象,设置url访问地址
        String uri = "https://www.csdn.net/";
        HttpGet httpGet = new HttpGet(uri);

        //配置请求信息
        RequestConfig.Builder config = RequestConfig.custom().setConnectTimeout( 1000 );//创建链接的最长时间,单位毫秒
        config.setConnectionRequestTimeout( 500 );//设置获取链接的最长时间,单位毫秒
        config.setSocketTimeout( 10*1000 );//设置数据传输的最长时间,单位毫秒
        config.build();

        //给请求设置请求信息
        httpGet.setConfig( RequestConfig.custom().build());

        //try/catch/finally : Ctrl+Alt+T
        CloseableHttpResponse response = null;
        try {
            //使用HttpClient发起请求,获取response
            response = httpClient.execute(httpGet);

            //解析响应
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "utf8");
                System.out.println(content.length());
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭response
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

日常生活中我们会遇到网络问题导致爬取不能立即完成,这时我们就需要通过配置请求的设置建立延时连接。

        //配置请求信息
        //创建链接的最长时间,单位毫秒
        RequestConfig.Builder config = RequestConfig.custom().setConnectTimeout( 1000 );
        //设置获取链接的最长时间,单位毫秒
        config.setConnectionRequestTimeout( 500 );
        //设置数据传输的最长时间,单位毫秒
        config.setSocketTimeout( 10*1000 );
        config.build();

        //给请求设置请求信息
        httpGet.setConfig( RequestConfig.custom().build());

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!