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

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

简单使用

引入依赖


    <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>

一个简单的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();
        }


    }

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

使用代理

设置超时时间

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

先连接,后读取。

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

参考文档

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

参考视频

一头扎进HttpClient

猜你喜欢

转载自www.cnblogs.com/fonxian/p/10855973.html