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();
            }
        }
    }
}
相关推荐
火烧屁屁啦1 天前
【JavaEE进阶】初始Spring Web MVC
java·spring·java-ee
Theodore_10221 天前
4 软件工程——总体设计
java·开发语言·数据库·算法·java-ee·软件工程·设计
Theodore_10221 天前
1 软件工程——概述
java·开发语言·算法·设计模式·java-ee·软件工程·个人开发
天使day2 天前
SpringMVC
java·spring·java-ee
寻找沙漠的人2 天前
理解JVM
java·jvm·java-ee
寻找沙漠的人3 天前
JavaEE 导读与环境配置
java·spring boot·java-ee
Theodore_10223 天前
3 需求分析
java·开发语言·算法·java-ee·软件工程·需求分析·需求
神的孩子都在歌唱3 天前
Java 和 J2EE 有什么不同?
java·开发语言·java-ee
程序员大金3 天前
基于SSM+Vue的个性化旅游推荐系统
前端·vue.js·mysql·java-ee·tomcat·mybatis·旅游