httpClient请求

复制代码
package com.neusoft.common.utils;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;

@Slf4j
public class HttpClientUtil {
    /**
     *  通过httpClient发送get请求
     * @param url
     * @param params
     * @return
     * @throws IOException
     */
    public static String sendGetRequest(String url, Map<String,Object> headers,Map<String,Object> params) throws IOException {
        //创建HttpClient对象
        HttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet();

        // 设置请求头
        httpGet.addHeader("Accept", "application/json");
        httpGet.addHeader("Connection", "keep-alive");
        httpGet.addHeader("Content-Type", "application/json; charset=utf-8");

        for (String key : headers.keySet()) {
            httpGet.addHeader(key,String.valueOf(headers.get(key)));
        }

        // 设置参数
        if (params != null && params.size() > 0) {
            StringBuilder newUrl = new StringBuilder(url + "?");
            params.forEach((k, v) -> newUrl.append(k).append("=").append(v).append("&"));
            httpGet.setURI(URI.create(newUrl.toString()));
        }

        String response;
        try {
            HttpResponse execute = httpClient.execute(httpGet);
            // 获取响应实体
            HttpEntity responseEntity = execute.getEntity();
            response = responseEntity != null ? EntityUtils.toString(responseEntity, "UTF-8") : "响应结果为null";
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        log.info("{}的GET请求结果为:{}",url,response);
        return response;
    }

    /**
     * 通过httpClient发送post请求
     * @param url
     * @param headerParams
     * @param requestBodyParams
     * @param files
     * @return
     * @throws IOException
     */
    public static String sendPostRequest(String url,
                                         Map<String,Object> headerParams,
                                         Map<String,Map<String,Object>> requestBodyParams,
                                         Map<String,File> files) throws IOException {
        //创建HttpClient对象
        HttpClient httpClient = HttpClients.createDefault();

        //创建HttpPost对象
        HttpPost httpPost = new HttpPost(url);

        //设置请求头信息
        httpPost.addHeader("Accept", "application/json");
        httpPost.addHeader("Connection", "keep-alive");
        httpPost.addHeader("Expect", "100-continue");
        if(headerParams!=null && CollectionUtils.isNotEmpty(headerParams.keySet())) {
            for (String key : headerParams.keySet()) {
                httpPost.setHeader(key, String.valueOf(headerParams.get(key)));
            }
        }

        // 设置请求体
        ContentType contentType = ContentType.create("multipart/form-data", Charset.forName("UTF-8"));
        MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532)
                .setCharset(Charset.forName("UTF-8"))
                .setContentType(contentType);
        if(files!=null && CollectionUtils.isNotEmpty(files.keySet())){
            for (String fileName : files.keySet()) {
                builder.addBinaryBody("file", toByteArray(files.get(fileName)), ContentType.MULTIPART_FORM_DATA, fileName);
            }
        }
        if(requestBodyParams!=null && CollectionUtils.isNotEmpty(requestBodyParams.keySet())) {
            for (String keyName : requestBodyParams.keySet()) {
                if(requestBodyParams.get(keyName)!=null &&
                        CollectionUtils.isNotEmpty(requestBodyParams.get(keyName).keySet())){
                    for (String dateType : requestBodyParams.get(keyName).keySet()) {
                        Object obj = requestBodyParams.get(keyName).get(dateType);
                        switch (dateType){
                            case "string":
                                // 添加字符串参数
                                builder.addTextBody(keyName, String.valueOf(obj), ContentType.MULTIPART_FORM_DATA);
                                break;
                            case "object":
                                ContentBody contentBody = new StringBody(String.valueOf(obj), ContentType.APPLICATION_JSON);
                                // 添加对象参数
                                builder.addPart(keyName, contentBody);
                                break;
                            case "array":
                                JSONArray jsonArray = new JSONArray(String.valueOf(obj));
                                for (Object objTemp : jsonArray) {
                                    JSONObject jsonObject = new JSONObject(String.valueOf(objTemp));
                                    for (String objKey : jsonObject.keySet()) {
                                        Object oj  = jsonObject.get(objKey);
                                      if(oj instanceof String){
                                          builder.addTextBody(objKey, String.valueOf(oj), ContentType.MULTIPART_FORM_DATA);

                                      }else if(oj instanceof  JSONObject){
                                          ContentBody contentBody2 = new StringBody(String.valueOf(oj), ContentType.APPLICATION_JSON);
                                          // 添加对象参数
                                          builder.addPart(objKey, contentBody2);
                                      }
                                    }
                                }
                            }


                        }
                    }

                }

            }

        HttpEntity multipart = builder.build();
        // 将参数设置到HttpPost对象中
        httpPost.setEntity(multipart);
        log.info("{}请求的body信息:{}",url,multipart);
        try  {
            //执行请求
            HttpResponse response = httpClient.execute(httpPost);
            //获取响应结果
            HttpEntity responseEntity = response.getEntity();
            String responseString = EntityUtils.toString(responseEntity, "UTF-8");
            log.info("{}的POST请求结果为:{}",url,response);
            return  responseString;

        } catch (IOException e) {
            log.error("url:{},请求异常{}:",url,e.getMessage());
            e.printStackTrace();
        } finally {
            try {
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "error";
    }

    /**
     *  delete请求
     * @param url
     * @return
     */
    public static String sendDeleteRequest(String url,Map<String,Object> headerParams){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            // 创建HttpDelete对象,设置URI
            HttpDelete httpDelete = new HttpDelete(url);
            // 设置请求头
            for (String key : headerParams.keySet()) {
                httpDelete.setHeader(key,String.valueOf(headerParams.get(key)));
            }

            // 执行请求
            CloseableHttpResponse response = httpClient.execute(httpDelete);
            try {
                // 获取响应实体
                String responseBody = EntityUtils.toString(response.getEntity());
                log.info("{}请求的结果为:{}",url,responseBody);
                return  responseBody;
            } finally {
                // 关闭响应对象
                response.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭HttpClient实例
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return  "error";
    }


    public static byte[] toByteArray(File file) throws IOException {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            byte[] bytes = new byte[(int) file.length()];
            fis.read(bytes);
            return bytes;
        } finally {
            if (fis != null) {
                fis.close();
            }
        }
    }
}
相关推荐
AllenIverrui13 小时前
MyBatisPlus的使用
spring boot·spring·java-ee·mybatis
我焦虑的编程日记17 小时前
【Java EE】验证码案例
java·java-ee
炙热的大叔17 小时前
JavaEE初阶-网络编程
网络·java-ee
Jinyi50318 小时前
Spring Boot 高级配置:如何轻松定义和读取自定义配置
java·spring boot·后端·spring·java-ee·maven·intellij-idea
细心的莽夫20 小时前
集合复习(java)
java·开发语言·笔记·学习·java-ee
《黑巧克力》1 天前
【JavaEE】多线程进阶
java·spring·java-ee·maven·dubbo·idea
Gratitute_林腾1 天前
MyBatisPlus-分页插件的基本使用
java·java-ee
hummhumm1 天前
数据结构第3节: 抽象数据类型
数据结构·spring boot·spring·spring cloud·java-ee·maven·intellij-idea
我焦虑的编程日记1 天前
【Java EE】Mybatis操作数据库
数据库·java-ee·mybatis
飞翔的佩奇1 天前
Java项目:基于SSM框架实现的智慧城市实验室管理系统分前后台【ssm+B/S架构+源码+数据库+毕业论文】
java·数据库·架构·java-ee·maven·智慧城市·ssm框架