客户端编程工具包 HttpClient

一、介绍

HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议

1、作用

  • 发送 HTTP 请求
  • 接收响应数据

2、应用场景

当我们在使用扫描支付、查看地图、获取验证码、查看天气等功能时
其实,应用程序本身并未实现这些功能,都是在应用程序里访问提供这些功能的服务,访问这些服务需要发送 HTTP 请求,并且接收响应数据,可通过 HttpClient 来实现

3、核心 API

  • HttpClient:Http 客户端对象类型,使用该类型对象可发起 Http 请求
  • HttpClients:可认为是构建器,可创建 HttpClient 对象
  • CloseableHttpClient:实现类,实现了 HttpClient 接口
  • HttpGet:Get 方式请求类型
  • HttpPost:Post 方式请求类型

4、请求步骤

  • 创建 HttpClient 对象
  • 创建 Http 请求对象
  • 调用 HttpClient 的 execute 方法发送请求

二、编码使用

1、导入 Maven 坐标

xml 复制代码
<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
</dependency>

2、发送 Get 请求

步骤:

  1. 创建HttpClient对象
  2. 创建请求对象
  3. 发送请求,接受响应结果
  4. 解析结果
  5. 关闭资源

编码:

java 复制代码
@SpringBootTest
public class HttpClientTest {

    /**
     * 测试httpclient发送GET方式的请求
     */
    @Test
    public void testGET() throws Exception{
        //1.创建httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        //2.创建请求对象
        HttpGet httpGet = new HttpGet("http://localhost:8080/test");

        //3.发送请求,接受响应结果
        CloseableHttpResponse response = httpClient.execute(httpGet);

        //4.解析结果
        int statusCode = response.getStatusLine().getStatusCode();
        System.out.println("服务端返回的状态码为:" + statusCode);

        HttpEntity entity = response.getEntity();
        String body = EntityUtils.toString(entity);
        System.out.println("服务端返回的数据为:" + body);

        //5.关闭资源
        response.close();
        httpClient.close();
    }
}

3、发送 Post 请求

步骤:

  1. 创建HttpClient对象
  2. 创建请求对象
  3. 发送请求,接受响应结果
  4. 解析结果
  5. 关闭资源

编码:

java 复制代码
@SpringBootTest
public class HttpClientTest {

    /**
     * 测试httpclient发送POST方式的请求
     */
    @Test
    public void testPOST() throws Exception{
        //1.创建httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        //2.创建请求对象
        HttpPost httpPost = new HttpPost("http://localhost:8080/test");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username","admin");
        jsonObject.put("password","123456");

        StringEntity entity = new StringEntity(jsonObject.toString());
        //指定请求编码方式
        entity.setContentEncoding("utf-8");
        //数据格式
        entity.setContentType("application/json");
        httpPost.setEntity(entity);

        //3.发送请求
        CloseableHttpResponse response = httpClient.execute(httpPost);

        //4.解析返回结果
        int statusCode = response.getStatusLine().getStatusCode();
        System.out.println("响应码为:" + statusCode);

        HttpEntity entity1 = response.getEntity();
        String body = EntityUtils.toString(entity1);
        System.out.println("响应数据为:" + body);

        //5.关闭资源
        response.close();
        httpClient.close();
    }
}

三、封装 HttpClientUtil 工具类

java 复制代码
/**
 * Http工具类
 */
public class HttpClientUtil {

    static final int TIMEOUT_MSEC = 5 * 1000;

    /**
     * 发送GET方式请求
     * @param url
     * @param paramMap
     * @return
     */
    public static String doGet(String url,Map<String,String> paramMap){
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        String result = "";
        CloseableHttpResponse response = null;

        try{
            URIBuilder builder = new URIBuilder(url);
            if(paramMap != null){
                for (String key : paramMap.keySet()) {
                    builder.addParameter(key,paramMap.get(key));
                }
            }
            URI uri = builder.build();

            //创建GET请求
            HttpGet httpGet = new HttpGet(uri);

            //发送请求
            response = httpClient.execute(httpGet);

            //判断响应状态
            if(response.getStatusLine().getStatusCode() == 200){
                result = EntityUtils.toString(response.getEntity(),"UTF-8");
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                response.close();
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return result;
    }

    /**
     * 发送POST方式请求
     * @param url
     * @param paramMap
     * @return
     * @throws IOException
     */
    public static String doPost(String url, Map<String, String> paramMap) throws IOException {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";

        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);

            // 创建参数列表
            if (paramMap != null) {
                List<NameValuePair> paramList = new ArrayList();
                for (Map.Entry<String, String> param : paramMap.entrySet()) {
                    paramList.add(new BasicNameValuePair(param.getKey(), param.getValue()));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }

            httpPost.setConfig(builderRequestConfig());

            // 执行http请求
            response = httpClient.execute(httpPost);

            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }

    /**
     * 发送POST方式请求
     * @param url
     * @param paramMap
     * @return
     * @throws IOException
     */
    public static String doPost4Json(String url, Map<String, String> paramMap) throws IOException {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";

        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);

            if (paramMap != null) {
                //构造json格式数据
                JSONObject jsonObject = new JSONObject();
                for (Map.Entry<String, String> param : paramMap.entrySet()) {
                    jsonObject.put(param.getKey(),param.getValue());
                }
                StringEntity entity = new StringEntity(jsonObject.toString(),"utf-8");
                //设置请求编码
                entity.setContentEncoding("utf-8");
                //设置数据类型
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
            }

            httpPost.setConfig(builderRequestConfig());

            // 执行http请求
            response = httpClient.execute(httpPost);

            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }
    private static RequestConfig builderRequestConfig() {
        return RequestConfig.custom()
                .setConnectTimeout(TIMEOUT_MSEC)
                .setConnectionRequestTimeout(TIMEOUT_MSEC)
                .setSocketTimeout(TIMEOUT_MSEC).build();
    }

}
相关推荐
MrZhangBaby13 分钟前
SQL-leetcode—1158. 市场分析 I
java·sql·leetcode
一只淡水鱼6627 分钟前
【spring原理】Bean的作用域与生命周期
java·spring boot·spring原理
五味香33 分钟前
Java学习,查找List最大最小值
android·java·开发语言·python·学习·golang·kotlin
jerry-891 小时前
Centos类型服务器等保测评整/etc/pam.d/system-auth
java·前端·github
Jerry Lau1 小时前
大模型-本地化部署调用--基于ollama+openWebUI+springBoot
java·spring boot·后端·llama
小白的一叶扁舟1 小时前
Kafka 入门与应用实战:吞吐量优化与与 RabbitMQ、RocketMQ 的对比
java·spring boot·kafka·rabbitmq·rocketmq
幼儿园老大*1 小时前
【系统架构】如何设计一个秒杀系统?
java·经验分享·后端·微服务·系统架构
言之。1 小时前
【Java】面试中遇到的两个排序
java·面试·排序算法
计算机-秋大田1 小时前
基于SSM的家庭记账本小程序设计与实现(LW+源码+讲解)
java·前端·后端·微信小程序·小程序·课程设计
南宫生1 小时前
力扣动态规划-7【算法学习day.101】
java·数据结构·算法·leetcode·动态规划