IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 网络协议 -> [java]封装 httpClient 工具类发送 post & delete & put 的 http 请求(带参数 + digest 认证) -> 正文阅读

[网络协议][java]封装 httpClient 工具类发送 post & delete & put 的 http 请求(带参数 + digest 认证)

先说下背景:我最近负责的项目,需要调用第三方接口,发送 get/post/put/delete 请求,这些请求有的需要经过 digest 认证,有的则不需要进行 digest 认证,直接请求就可以了
get 请求还好说一些,直接使用 hutool 工具类中的 get 请求就可以满足需要,那你可能会说, hutool 工具类也支持 post 请求呀,但是如果我的 post 请求需要以 form-data 形式提交,它就不满足了,而且 hutool 工具类也不支持发送 put/delete 请求

所以我就自己写了个工具类,不过我写的这个比较粗糙,放在这里,有需要的人看着拿吧~回头我有时间的话,就再优化一下:

public class HttpUtils {
    /**
     * 以 post 方式调用第三方接口,以 form-data 形式  发送 MultipartFile 文件数据
     *
     * @param url  post请求url
     * @param fileParamName 文件参数名称
     * @param multipartFile  文件
     * @param paramMap 表单里其他参数
     * @return
     */
    public static String doPostFormData(String url, String fileParamName, MultipartFile multipartFile, Map<String, String> paramMap) {

        // 创建 Http 实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建 HttpPost 实例
        HttpPost httpPost = new HttpPost(url);

        // 请求参数配置
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000)
                .setConnectionRequestTimeout(10000).build();
        httpPost.setConfig(requestConfig);

        try {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create()
                    .setCharset(Consts.UTF_8);
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

            // 设置 content-type
            builder.setContentType(ContentType.MULTIPART_FORM_DATA);
            builder.setCharset(StandardCharsets.UTF_8);
            // 待上传文件
            FormBodyPart part = FormBodyPartBuilder.create()
                    .setName(fileParamName)
                    .setBody(new ByteArrayBody(
                            multipartFile.getBytes(),
                            ContentType.create(multipartFile.getContentType(), StandardCharsets.UTF_8),
                            multipartFile.getOriginalFilename()))
                    .build();
            builder.addPart(part);

            // 表单中其他参数
            if(paramMap != null) {
                for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                    builder.addPart(FormBodyPartBuilder.create()
                            .setName(entry.getKey())
                            .setBody(new StringBody(entry.getValue(),
                                    ContentType.create(
                                            ContentType.TEXT_PLAIN.getMimeType(),
                                            StandardCharsets.UTF_8)))
                            .build());
                }
            }

            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            // 执行提交
            HttpResponse response = httpClient.execute(httpPost);

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 返回
                String res = EntityUtils.toString(response.getEntity(), java.nio.charset.Charset.forName("UTF-8"));
                return res;
            }else {
                HttpEntity responseEntity = response.getEntity();
                byte[] msg = new byte[(int) responseEntity.getContentLength()];
                responseEntity.getContent().read(msg);
                log.error("error msg: {}", new String(msg));
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error("调用 HttpPost 失败!" + e.toString());
        } finally {
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    log.error("关闭 HttpPost 连接失败!");
                }
            }
        }
        return null;
    }

    /**
     * 发送 http delete 请求
     */
    public static String doDelete(JSONObject dataMap, String url, Boolean flag){
        CloseableHttpClient client = null;
        if(flag){
            client = digestHttpClient(null,null);
        }else {
            client = HttpClients.createDefault();
        }
        HttpDeleteWithBodyUtil httpDelete = null;
        String result = null;
        try {
            httpDelete = new HttpDeleteWithBodyUtil(url);

            httpDelete.addHeader("Content-type","application/json; charset=utf-8");
            httpDelete.setHeader("Accept", "application/json; charset=utf-8");
            if (dataMap != null){
                StringEntity stringEntity = new StringEntity(dataMap.toJSONString(),"UTF-8");
                httpDelete.setEntity(stringEntity);
            }

            CloseableHttpResponse response = client.execute(httpDelete);

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 返回
                String res = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
                return res;
            } else {
                HttpEntity responseEntity = response.getEntity();
                byte[] msg = new byte[(int) responseEntity.getContentLength()];
                responseEntity.getContent().read(msg);
                JSONObject parse = JSONObject.parseObject(new String(msg));
                log.error("error msg: {}", parse);
            }
        } catch (Exception e) {
            log.error("发送 http delete 请求时出现错误,请求路径: {} ,错误信息: {}",url, e.toString());
        } finally {
            if (client != null) {
                try {
                    client.close();
                } catch (IOException e) {
                    log.error("关闭 HttpPost 连接失败!");
                }
            }
        }
        return null;
    }

    /**
     * 发送 http put 请求
     */
    public static String doPut(JSONObject dataMap, String url, Boolean flag){
        CloseableHttpClient client = null;
        if(flag){
            client = digestHttpClient(null,null);
        }else {
            client = HttpClients.createDefault();
        }
        String result = null;
        try {
            HttpPut httpPut = new HttpPut(url);

            httpPut.addHeader("Content-Type", "application/json");
            if (dataMap != null) {
                StringEntity stringEntity = new StringEntity(dataMap.toJSONString());
                httpPut.setEntity(stringEntity);
            }
            // 从响应模型中获得具体的实体
            HttpResponse response = client.execute(httpPut);

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 返回
                String res = EntityUtils.toString(response.getEntity(), java.nio.charset.Charset.forName("UTF-8"));
                return res;
            }else {
                HttpEntity responseEntity = response.getEntity();
                byte[] msg = new byte[(int) responseEntity.getContentLength()];
                responseEntity.getContent().read(msg);
                JSONObject parse = JSONObject.parseObject(new String(msg));
                log.error("error msg: {}", new String(msg));
            }
        } catch (Exception e) {
            log.error("发送 http put 请求时出现错误,请求路径: {} ,错误信息: {}",url, e.toString());
        } finally {
            if (client != null) {
                try {
                    client.close();
                } catch (IOException e) {
                    log.error("关闭 HttpPut 连接失败!");
                }
            }
        }
        return null;
    }

    /**
     * 发送 http post 请求
     */
    public static String doPost(JSONObject dataMap, String url, Boolean flag){
        CloseableHttpClient client = null;
        if(flag){
            client = digestHttpClient(null,null);
        }else {
            client = HttpClients.createDefault();
        }
        String result = null;
        try {
            HttpPost httpPost = new HttpPost(url);

            httpPost.addHeader("Content-Type", "application/json");
            if (dataMap != null) {
                StringEntity s = new StringEntity(dataMap.toString(),"UTF-8");
                s.setContentEncoding("UTF-8");
                s.setContentType("application/json");
                httpPost.setEntity(s);
            }
            // 从响应模型中获得具体的实体
            HttpResponse response = client.execute(httpPost);

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 返回
                String res = EntityUtils.toString(response.getEntity(), java.nio.charset.Charset.forName("UTF-8"));
                return res;
            } else {
                HttpEntity entity = response.getEntity();
                byte[] msg = new byte[(int) entity.getContentLength()];
                entity.getContent().read(msg);
                JSONObject parse = JSONObject.parseObject(new String(msg));
                log.error("error msg: {}", parse);
            }
        } catch (Exception e) {
            log.error("发送 http post 请求时出现错误,请求路径: {} ,错误信息: {}",url, e.toString());
        } finally {
            if (client != null) {
                try {
                    client.close();
                } catch (IOException e) {
                    log.error("关闭 HttpPost 连接失败!");
                }
            }
        }
        return null;
    }


    /**
     * 以 post 方式调用第三方接口,以 form-data 形式  发送 MultipartFile 文件数据 & 数组
     */
    public static String doPostFormDataByArray(String url, String fileParamName, MultipartFile multipartFile, Map<String, Object> paramMap) {

        // 创建 Http 实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建 HttpPost 实例
        HttpPost httpPost = new HttpPost(url);

        // 请求参数配置
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000)
                .setConnectionRequestTimeout(10000).build();
        httpPost.setConfig(requestConfig);

        try {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create()
                    .setCharset(Consts.UTF_8);
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

            // 设置 content-type
            builder.setContentType(ContentType.MULTIPART_FORM_DATA);
            builder.setCharset(StandardCharsets.UTF_8);
            // 待上传文件
            FormBodyPart part = FormBodyPartBuilder.create()
                    .setName(fileParamName)
                    .setBody(new ByteArrayBody(
                            multipartFile.getBytes(),
                            ContentType.create(multipartFile.getContentType(), StandardCharsets.UTF_8),
                            multipartFile.getOriginalFilename()))
                    .build();
            builder.addPart(part);

            // 表单中其他参数 -- 数组类型
            if(paramMap != null) {
                for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
                    String name = entry.getKey();
                    Object value = entry.getValue();
                    builder.addPart(FormBodyPartBuilder.create()
                            .setName(name)
                            .setBody(new StringBody(value.toString(),
                                    ContentType.create(
                                            ContentType.TEXT_PLAIN.getMimeType(),
                                            StandardCharsets.UTF_8)))
                            .build());
                }
            }

            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            // 执行提交
            HttpResponse response = httpClient.execute(httpPost);

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 返回
                String res = EntityUtils.toString(response.getEntity(), java.nio.charset.Charset.forName("UTF-8"));
                return res;
            } else {
                HttpEntity responseEntity = response.getEntity();
                byte[] msg = new byte[(int) responseEntity.getContentLength()];
                responseEntity.getContent().read(msg);
                JSONObject parse = JSONObject.parseObject(new String(msg));
                log.error("error msg: {}", parse);
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error("调用 HttpPost 失败!" + e.toString());
        } finally {
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    log.error("关闭 HttpPost 连接失败!");
                }
            }
        }
        return null;
    }

    public static CloseableHttpClient digestHttpClient(String host, Integer port){
        String username = UserUtils.username;
        String password = UserUtils.password;
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(StringUtils.isEmpty(host) ? AuthScope.ANY_HOST : host, port == null ? AuthScope.ANY_PORT : port),
                new UsernamePasswordCredentials(username,password));
        return HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();
    }
public class HttpDeleteWithBodyUtil extends HttpEntityEnclosingRequestBase {
   public static final String METHOD_NAME = "DELETE";

    /**
     * 获取方法(必须重载)
     *
     * @return
     */
    @Override
    public String getMethod() {
        return METHOD_NAME;
    }

    public HttpDeleteWithBodyUtil(final String uri) {
        super();
        setURI(URI.create(uri));
    }

    public HttpDeleteWithBodyUtil(final URI uri) {
        super();
        setURI(uri);
    }

    public HttpDeleteWithBodyUtil() {
        super();
    }
}

我刚刚在看资料的时候,发现还有 okhttpclient 和 restTemplate ,感兴趣的小伙伴也可以看看这块~
以上,感谢您的阅读哇

  网络协议 最新文章
使用Easyswoole 搭建简单的Websoket服务
常见的数据通信方式有哪些?
Openssl 1024bit RSA算法---公私钥获取和处
HTTPS协议的密钥交换流程
《小白WEB安全入门》03. 漏洞篇
HttpRunner4.x 安装与使用
2021-07-04
手写RPC学习笔记
K8S高可用版本部署
mySQL计算IP地址范围
上一篇文章      下一篇文章      查看所有文章
加:2021-10-17 12:19:05  更:2021-10-17 12:19:18 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年6日历 -2024/6/29 18:00:02-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码