HttpClient学习(一)—— 基本使用

HttpClient是支持Http协议的客户端编程工具包。

一、简单使用

1.1 引入依赖


	<dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.5</version>
    </dependency>

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.47</version>
    </dependency>

1.2 一个简单的Get请求


public static void main(String[] args) {
        //创建HttpClient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建HttpGet实例
        HttpGet httpGet = new HttpGet("http://www.baidu.com");
        CloseableHttpResponse response = null;
        //执行Get请求
        try {
            response = httpClient.execute(httpGet);
            //获取实体
            HttpEntity httpEntity = response.getEntity();
            //解析实体
            System.out.println(EntityUtils.toString(httpEntity,"utf-8"));
            response.close();
            httpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }


1.3 Post请求、请求头、请求参数

1.4 使用代理

1.5 设置超时时间

HttpClient内部有三个超时时间设置:连接池获取可用连接超时,连接超时,读取数据超时

先连接,后读取。

RequestConfig requestConfig = RequestConfig.custom()  
		//从连接池中获取连接的超时时间  
        .setConnectTimeout(5000)
        //httpclient会创建一个异步线程用以创建socket连接,此处设置该socket的连接超时时间  
        .setConnectionRequestTimeout(1000)  
        //socket读数据超时时间:从服务器获取响应数据的超时时间
        .setSocketTimeout(5000)
        .build();  
httpGet.setConfig(requestConfig);  

参考文档

HttpClient源码解析系列:第二篇:极简版实现
HttpClient官网 Quick Start

参考视频

一头扎进HttpClient

posted @ 2019-05-13 12:30  清泉白石  阅读(651)  评论(0编辑  收藏  举报