
大家好 , 我是苏麟 , 今天带来一个HTTP通信库 HttpClient .
HttpClient是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包 .
HttpClient的功能包括但不限于
1.模拟浏览器发送HTTP请求,发送请求参数,并接收响应
2.RPC接口调用
3.爬取网页源码
HttpClient优点
基于标准、纯净的java语言。实现了HTTP1.0和HTTP1.1;
以可扩展的面向对象的结构实现了HTTP全部的方法(GET, POST等7种方法);
支持HTTPS协议;
官方文档 : Apache HttpComponents – HttpClient Overview

开始使用
引入依赖
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency> 
Get请求
public class HttpClientDemo {
    public static void main(String[] args) {
        //请求地址
        String url = "";
        //1.创建HttpClient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //2.使用get请求,创建HttpGet对象
        HttpGet get = new HttpGet(url);
        try {
            //3.发起请求, 使用client对象
            // CloseableHttpResponse:表示访问url后,对方给你返回的结果
            CloseableHttpResponse response = client.execute(get);
            //4.通过response获取请求的数据
            String result = EntityUtils.toString(response.getEntity());
            System.out.println("访问地址后,得到结果内容:" + result);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭client
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
} 
Post请求
public class HttpClientDemo {
    public static void main(String[] args) {
        //测试使用HttpClient的post请求
        //https://restapi.amap.com/v3/ip?key=0113a13c88697dcea6a445584d535837&ip="
        String url = "https://restapi.amap.com/v3/ip";
        //1创建HttpClient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //2.创建HttpPost对象
        HttpPost post = new HttpPost(url);
        //3.给post请求,指定请求的参数, 参数名称=值的方式
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("key", "0113a13c88697dcea6a445584d535837"));
        params.add(new BasicNameValuePair("ip", "39.137.95.111"));
        try {
            //添加其他的参数
            HttpEntity entity = new UrlEncodedFormEntity(params);
            post.setEntity(entity);
            //执行请求
            CloseableHttpResponse response = client.execute(post);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String str = EntityUtils.toString(response.getEntity());
                System.out.println("返回结果 : " + str);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
 
想要更深入了解请去官网 !
这期就到这里 , 拜拜 !




![linux学习(文件描述符)[12]](https://img-blog.csdnimg.cn/8ecab7fc89464e08a4f73d030de19550.png)














