因为jdk原生http api较为繁琐,这个框架封装了相关操作

1 引入jar包

  1. <!--添加httpClient jar包 -->
  2. <dependency>
  3. <groupId>org.apache.httpcomponents</groupId>
  4. <artifactId>httpclient</artifactId>
  5. </dependency>

2 入门案例

public class HttpClientTest {

    @Test
    public void testGet() throws IOException {
        String url = "https://www.baidu.com/";
        //创建httpClient客户端对象
        HttpClient httpClient = HttpClients.createDefault();
        //创建请求类型
        HttpGet httpGet = new HttpGet(url);
        //发起http请求.并且获取响应的结果
        HttpResponse httpResponse = httpClient.execute(httpGet);
        //判断状态码是否为200 如果等于200则请求正确
        if(httpResponse.getStatusLine().getStatusCode() == 200) {
            //表示用户请求正确
            //获取返回值数据
            HttpEntity httpEntity = httpResponse.getEntity();
            String result = EntityUtils.toString(httpEntity, "UTF-8");
            System.out.println(result);
        }
    }
}

在基本应用中与以下几个类相关

HttpClient 客户端对象,基于此对象发送请求
HttpGet 封装get请求
HttpPost 封装post请求
HttpResponse 返回值对象,Response对象,封装了返回信息
HttpEntity 封装Response的内容
EntityUtils 处理HttpEntity的工具类
RequsestConfig 连接设置类

反正在idea中都可以“.”出来,瞎试就行需要注意下的有以下几个
设置连接配置

RequestConfig.Builder custom = RequestConfig.custom();
        custom.setConnectTimeout(13);

        CloseableHttpClient aDefault = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet("http://www.baidu.com");
        httpGet.setConfig(custom.build());//我猜的

异步请求