当前位置: 首页 > article >正文

SpringBoot(二十一)SpringBoot自定义CURL请求类

在测试SpringAi的时候,发现springAI比较人性化的地方,他为开发者提供了多种请求方式,如下图所示:

1.png.jpg

上边的三种方式里边,我还是喜欢CURL,巧了,我还没在Springboot框架中使用过CURL呢。正好封装一个CURL工具类。

我这里使用httpclient来实现CURL请求。

一:添加依赖

不需要任何第三方依赖,对,就是这样。

二:实现请求

1:封装POST请求,代码如下:

/**
 * @name CURL POST 请求
 * @param url     接口地址
 * @param list    NameValuePair(简单名称值对节点类型)类似html中的input
 * @param headers 请求头(默认Content-Type:application/x-www-form-urlencoded; charset=UTF-8)
 * 请求示例
    // 设置请求头
    Map<String, String> headers = new HashMap<>();
    headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36");
    // 设置请求参数
    ArrayList<NameValuePair> list = new ArrayList<>();
    list.add(new BasicNameValuePair("indexName", "test"));
    // 发送请求
    String s = CurlRequest.curlPost("http://localhost:7001/java/elastic/indexIsExists", list, headers);
    System.out.println(s);
 */
public static Map<String, Object> curlPost(String url, ArrayList<NameValuePair> list, Map<String, String> headers)
{
    String StringResult = "";
    CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);
    if (list != null && !list.isEmpty())
    {
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list, Consts.UTF_8);
        httpPost.setEntity(formEntity);
    }
    httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    if (headers != null && !headers.isEmpty())
    {
        for (String head : headers.keySet())
        {
            httpPost.addHeader(head, headers.get(head));
        }
    }
    CloseableHttpResponse response = null;
    try
    {
        response = closeableHttpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        StringResult = EntityUtils.toString(entity, StandardCharsets.UTF_8);
        EntityUtils.consume(entity);
    }
    catch (Exception e)
    {
        StringResult = "errorException:" + e.getMessage();
        e.printStackTrace();
    }
    finally
    {
        checkObjectIsNull(closeableHttpClient, response);
    }
    return Function.convertJsonToMap(StringResult);
}
/**
 * 判断对象是否为Null
 * @param closeableHttpClient
 * @param response
 */
private static void checkObjectIsNull(CloseableHttpClient closeableHttpClient, CloseableHttpResponse response)
{
    if(response != null)
    {
        try
        {
            response.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
    if (closeableHttpClient != null)
    {
        try
        {
            closeableHttpClient.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

调用测试:

@GetMapping("index/testsss")
public void testsss()
{
    // 测试CURLPOST
    // 设置请求头
    Map<String, String> headers = new HashMap<>();
    headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36");
    // 设置请求参数
    ArrayList<NameValuePair> list = new ArrayList<>();
    list.add(new BasicNameValuePair("indexName", "test"));
    // 发送请求
    String s = CurlRequest.curlPost("http://localhost:7001/java/elastic/indexIsExists", list, headers);
    System.out.println(s);
}

2:封装GET请求,代码如下:

/**
 * @param url    获取get请求URL地址(无参数/有参)
 * @param params 拼接参数集合
 * @Description get请求URL拼接参数 & URL编码
 * 请求示例
    // 设置请求参数
    Map<String, String> params = new HashMap<>();
    params.put("search", "服务");
    // 获取请求链接
    String appendUrl = CurlRequest.getCurlGetUrl("http://localhost:7001/java/index/getArticleListByCategory?page=1", params);
    System.out.println(appendUrl);
 */
public static String getCurlGetUrl(String url, Map<String, String> params)
{
    StringBuffer buffer = new StringBuffer(url);
    if (params != null && !params.isEmpty())
    {
        for (String key : params.keySet())
        {
            if (buffer.indexOf("?") >= 0)
            {
                buffer.append("&");
            }
            else
            {
                buffer.append("?");
            }
            String value = "";
            //value = params.get(key);
            try
            {
                 value = URLEncoder.encode(params.get(key), StandardCharsets.UTF_8.name());
            }
            catch (UnsupportedEncodingException e)
            {
                e.printStackTrace();
            }//*/
            buffer.append(key)
                    .append("=")
                    .append(value);
        }
    }
    return buffer.toString();
}

/**
 * @param url     接口地址
 * @param headers 请求头
 * @Description get请求
 * 请求示例
    // 设置请求头
    Map<String, String> headers = new HashMap<>();
    headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36");
    // 设置请求参数
    Map<String, String> params = new HashMap<>();
    params.put("search", "服务");
    // 获取请求链接
    String appendUrl = CurlRequest.getCurlGetUrl("http://localhost:7001/java/index/getArticleListByCategory?page=1", params);
    System.out.println(appendUrl);
    // 发送请求
    String postData = CurlRequest.curlGet(appendUrl,headers);
    System.out.println(postData);
 */
public static String curlGet(String url, Map<String, String> headers)
{
    String StringResult = "";
    CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(url);
    if (headers != null && !headers.isEmpty())
    {
        for (String head : headers.keySet())
        {
            httpGet.addHeader(head, headers.get(head));
        }
    }
    CloseableHttpResponse response = null;
    try
    {
        response = closeableHttpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        StringResult = EntityUtils.toString(entity, StandardCharsets.UTF_8).trim();
        EntityUtils.consume(entity);
    }
    catch (Exception e)
    {
        e.printStackTrace();
        StringResult = "errorException:" + e.getMessage();
    }
    finally
    {
        checkObjectIsNull(closeableHttpClient, response);
    }
    return StringResult;
}

/**
 * 判断对象是否为Null
 * @param closeableHttpClient
 * @param response
 */
private static void checkObjectIsNull(CloseableHttpClient closeableHttpClient, CloseableHttpResponse response)
{
    if(response != null)
    {
        try
        {
            response.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
    if (closeableHttpClient != null)
    {
        try
        {
            closeableHttpClient.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

测试一下:

@GetMapping("index/testsss")
public void testsss()
{
// 测试CURLGET
// 设置请求头
Map<String, String> getheaders = new HashMap<>();
getheaders.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36");
// 设置请求参数
Map<String, String> params = new HashMap<>();
params.put("search", "服务");
// 获取请求链接
String appendUrl = CurlRequest.getCurlGetUrl("http://localhost:7001/java/index/getArticleListByCategory?page=1", params);
System.out.println(appendUrl);
// 发送请求
String postData = CurlRequest.curlGet(appendUrl,getheaders);
System.out.println(postData);//*/
}

3:POST异步请求

/**
 * @name 异步 CURL POST 请求
 * @param url     接口地址
 * @param list    NameValuePair(简单名称值对节点类型)类似html中的input
 * @param headers 请求头(默认Content-Type:application/x-www-form-urlencoded; charset=UTF-8)
 * 请求示例
    ArrayList<NameValuePair> asynclist = new ArrayList<>();
    asynclist.add(new BasicNameValuePair("indexName", "test"));
    asynclist.add(new BasicNameValuePair("id", "90"));
    // 设置请求头
    Map<String, String> asyncHeaders = new HashMap<>();
    asyncHeaders.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36");
    // 发送请求
    Map<String,Object> async = CurlRequest.asyncCurlPost("http://localhost:7001/java/elastic/documentIsExists", asynclist, asyncHeaders);
    System.out.println(async);
    return "我在tessss方法中……";
 */
public static Map<String, Object> asyncCurlPost(String url, ArrayList<NameValuePair> list, Map<String, String> headers)
{
    String responseBody = "";
    // 创建异步HTTP客户端
    CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
    try
    {
        httpClient.start(); // 启动HttpClient

        // 创建Http Post请求
        HttpPost httpPost = new HttpPost(url);
        // 设置请求参数
        if (list != null && !list.isEmpty())
        {
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list, Consts.UTF_8);
            httpPost.setEntity(formEntity);
        }
        // 设置请求头
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        if (headers != null && !headers.isEmpty())
        {
            for (String head : headers.keySet())
            {
                httpPost.addHeader(head, headers.get(head));
            }
        }
        // 发送请求并获取Future对象
        Future<HttpResponse> future = httpClient.execute(httpPost, null);

        // 获取响应
        HttpResponse response = future.get();
        responseBody = EntityUtils.toString(response.getEntity());
        System.out.println("Response: " + responseBody);
    }
    catch (Exception e)
    {
        e.printStackTrace();
        System.out.println("请求出错了!");
    }
    finally
    {
        // 关闭HttpClient
        try
        {
            httpClient.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        Map<String, Object> result = new HashMap<>();
        result.put("code", 1);
        result.put("result", "异步请求发送成功!");
        result.put("responseBody", responseBody);
        return result;
    }
}

测试一下:

@GetMapping("index/testsss")
public void testsss()
{
    // 测试ASYNCCURLPOST
    // 发送请求
    Map<String,Object> async = CurlRequest.asyncCurlPost("http://localhost:7001/java/index/tessss", null, null);
    System.out.println(async);
}

/**
 * 测试CURL POST异步方法
 */
@PostMapping("index/tessss")
public String tessss()
{
    ArrayList<NameValuePair> asynclist = new ArrayList<>();
    asynclist.add(new BasicNameValuePair("indexName", "test"));
    asynclist.add(new BasicNameValuePair("id", "90"));
    // 设置请求头
    Map<String, String> asyncHeaders = new HashMap<>();
    asyncHeaders.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36");
    // 发送请求
    Map<String,Object> async = CurlRequest.asyncCurlPost("http://localhost:7001/java/elastic/documentIsExists", asynclist, asyncHeaders);
    System.out.println(async);
    return "我在tessss方法中……";
}

浏览器访问:http://localhost:7001/java/index/testsss

控制台输出:

我们先请求这个方法tessss,这个tessss方法的返回值反而后边输出,因此,异步请求成功

2.png.jpg

三:完整CURL请求类

package com.springbootblog.utils;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Future;

/**
 * 自定义curl类
 */
public class CurlRequest
{
    /**
     * @name CURL POST 请求
     * @param url     接口地址
     * @param list    NameValuePair(简单名称值对节点类型)类似html中的input
     * @param headers 请求头(默认Content-Type:application/x-www-form-urlencoded; charset=UTF-8)
     * 请求示例
        // 设置请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36");
        // 设置请求参数
        ArrayList<NameValuePair> list = new ArrayList<>();
        list.add(new BasicNameValuePair("indexName", "test"));
        // 发送请求
        String s = CurlRequest.curlPost("http://localhost:7001/java/elastic/indexIsExists", list, headers);
        System.out.println(s);
     */
    public static Map<String, Object> curlPost(String url, ArrayList<NameValuePair> list, Map<String, String> headers)
    {
        String StringResult = "";
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        if (list != null && !list.isEmpty())
        {
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list, Consts.UTF_8);
            httpPost.setEntity(formEntity);
        }
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        if (headers != null && !headers.isEmpty())
        {
            for (String head : headers.keySet())
            {
                httpPost.addHeader(head, headers.get(head));
            }
        }
        CloseableHttpResponse response = null;
        try
        {
            response = closeableHttpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            StringResult = EntityUtils.toString(entity, StandardCharsets.UTF_8);
            EntityUtils.consume(entity);
        }
        catch (Exception e)
        {
            StringResult = "errorException:" + e.getMessage();
            e.printStackTrace();
        }
        finally
        {
            checkObjectIsNull(closeableHttpClient, response);
        }
        return Function.convertJsonToMap(StringResult);
    }

    /**
     * @name 异步 CURL POST 请求
     * @param url     接口地址
     * @param list    NameValuePair(简单名称值对节点类型)类似html中的input
     * @param headers 请求头(默认Content-Type:application/x-www-form-urlencoded; charset=UTF-8)
     * 请求示例
        ArrayList<NameValuePair> asynclist = new ArrayList<>();
        asynclist.add(new BasicNameValuePair("indexName", "test"));
        asynclist.add(new BasicNameValuePair("id", "90"));
        // 设置请求头
        Map<String, String> asyncHeaders = new HashMap<>();
        asyncHeaders.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36");
        // 发送请求
        Map<String,Object> async = CurlRequest.asyncCurlPost("http://localhost:7001/java/elastic/documentIsExists", asynclist, asyncHeaders);
        System.out.println(async);
        return "我在tessss方法中……";
     */
    public static Map<String, Object> asyncCurlPost(String url, ArrayList<NameValuePair> list, Map<String, String> headers)
    {
        String responseBody = "";
        // 创建异步HTTP客户端
        CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
        try
        {
            httpClient.start(); // 启动HttpClient

            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 设置请求参数
            if (list != null && !list.isEmpty())
            {
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list, Consts.UTF_8);
                httpPost.setEntity(formEntity);
            }
            // 设置请求头
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            if (headers != null && !headers.isEmpty())
            {
                for (String head : headers.keySet())
                {
                    httpPost.addHeader(head, headers.get(head));
                }
            }
            // 发送请求并获取Future对象
            Future<HttpResponse> future = httpClient.execute(httpPost, null);

            // 获取响应
            HttpResponse response = future.get();
            responseBody = EntityUtils.toString(response.getEntity());
            System.out.println("Response: " + responseBody);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            System.out.println("请求出错了!");
        }
        finally
        {
            // 关闭HttpClient
            try
            {
                httpClient.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            Map<String, Object> result = new HashMap<>();
            result.put("code", 1);
            result.put("result", "异步请求发送成功!");
            result.put("responseBody", responseBody);
            return result;
        }
    }

    /**
     * @name 组装 GET 请求连接
     * @param url    获取get请求URL地址(无参数/有参)
     * @param params 拼接参数集合
     * @Description get请求URL拼接参数 & URL编码
     * 请求示例
        // 设置请求参数
        Map<String, String> params = new HashMap<>();
        params.put("search", "服务");
        // 获取请求链接
        String appendUrl = CurlRequest.getCurlGetUrl("http://localhost:7001/java/index/getArticleListByCategory?page=1", params);
        System.out.println(appendUrl);
     */
    public static String getCurlGetUrl(String url, Map<String, String> params)
    {
        StringBuffer buffer = new StringBuffer(url);
        if (params != null && !params.isEmpty())
        {
            for (String key : params.keySet())
            {
                if (buffer.indexOf("?") >= 0)
                {
                    buffer.append("&");
                }
                else
                {
                    buffer.append("?");
                }
                String value = "";
                //value = params.get(key);
                try
                {
                     value = URLEncoder.encode(params.get(key), StandardCharsets.UTF_8.name());
                }
                catch (UnsupportedEncodingException e)
                {
                    e.printStackTrace();
                }//*/
                buffer.append(key)
                        .append("=")
                        .append(value);
            }
        }
        return buffer.toString();
    }

    /**
     * @name CURL GET 请求
     * @param url     接口地址
     * @param headers 请求头
     * @Description get请求
     * 请求示例
        // 设置请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36");
        // 设置请求参数
        Map<String, String> params = new HashMap<>();
        params.put("search", "服务");
        // 获取请求链接
        String appendUrl = CurlRequest.getCurlGetUrl("http://localhost:7001/java/index/getArticleListByCategory?page=1", params);
        System.out.println(appendUrl);
        // 发送请求
        String postData = CurlRequest.curlGet(appendUrl,headers);
        System.out.println(postData);
     */
    public static Map<String, Object> curlGet(String url, Map<String, String> headers)
    {
        String StringResult = "";
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        if (headers != null && !headers.isEmpty())
        {
            for (String head : headers.keySet())
            {
                httpGet.addHeader(head, headers.get(head));
            }
        }
        CloseableHttpResponse response = null;
        try
        {
            response = closeableHttpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            StringResult = EntityUtils.toString(entity, StandardCharsets.UTF_8).trim();
            EntityUtils.consume(entity);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            StringResult = "errorException:" + e.getMessage();
        }
        finally
        {
            checkObjectIsNull(closeableHttpClient, response);
        }
        return Function.convertJsonToMap(StringResult);
    }

    /**
     * 判断对象是否为Null
     * @param closeableHttpClient
     * @param response
     */
    private static void checkObjectIsNull(CloseableHttpClient closeableHttpClient, CloseableHttpResponse response)
    {
        if(response != null)
        {
            try
            {
                response.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        if (closeableHttpClient != null)
        {
            try
            {
                closeableHttpClient.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

}

有好的建议,请在下方输入你的评论。


http://www.kler.cn/a/392918.html

相关文章:

  • 【MySQL】约束
  • linux设置主机名
  • ArkTs简单入门案例:简单的图片切换应用界面
  • 基于混合配准策略的多模态医学图像配准方法研究
  • Android Framework AMS(16)进程管理
  • AMD CPU下pytorch 多GPU运行卡死和死锁解决
  • Optional 函数式接口
  • Spark:不能创建Managed表,External表已存在...
  • PostgreSQL 页损坏如何修复
  • 【Linux】进程通信之管道
  • MySQL算数运算符基础:详解与入门
  • 绿色能源新视界:透明导电膜助力高效光伏
  • Mysql 创建用户并授权
  • Flink 开发工程应加载哪些依赖
  • JavaScript逆向爬虫教程-------基础篇之JavaScript密码学以及CryptoJS各种常用算法的实现
  • 英语中从句和复合句简单介绍
  • 老旧城区供水管网改造优先等级分析
  • stm32学习之路——八种GPIO口工作模式
  • el-form el-table 前端排序+校验+行编辑
  • LLMs之VDB:Elasticsearch的简介、安装和使用方法、案例应用之详细攻略
  • 服务器显卡和桌面pc显卡有什么不同
  • C++builder中的人工智能(17):神经网络中的自我规则非单调(Mish)激活函数
  • sklearn.datasets中make_classification函数
  • 3216. 交换后字典序最小的字符串
  • 单词反转和数组去重,附经典面试题一份
  • C/C++内存管理 | new的机制 | 重载自己的operator new