[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 ,感兴趣的小伙伴也可以看看这块~
以上,感谢您的阅读哇

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值