Java中的HTTP请求工具类(基础通用版)

43 阅读2分钟

1.引入依赖

<!--HttpClient-->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.12</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.5.3</version>
</dependency>

2.编写工具类

package com.web.common.utils;

import com.baomidou.mybatisplus.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
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.client.utils.URIBuilder;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @description: HTTP请求工具类
 **/
@Slf4j
public class HttpUtils {

    /**
     * GET请求,无需传参
     * @param url
     * @return java.lang.String
     */
    public static String doGet(String url) {
        return doGetMap(url, null);
    }

    /**
     * POST请求,无需传参
     * @param url
     * @return java.lang.String
     */
    public static String doPost(String url) {
        return doPostJson(url, null, null);
    }

    /**
     * GET请求,通过Map集合传参,返回Json字符串
     * @param url
     * @param map
     * @return java.lang.String
     */
    public static String doGetMap(String url, Map<String,String> map) {
        String result = "";
        try {
            //定义返回实例
            CloseableHttpResponse response = null;
            //创建GET请求
            URIBuilder builder = new URIBuilder(url);
            HttpGet httpGet = new HttpGet(builder.build());
            CloseableHttpClient httpClient = HttpClients.createDefault();
            //设置http的链接超时时间
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(60000)    //设置连接超时时间
                    .setSocketTimeout(60000)   //设置响应超时时间
                    .setConnectionRequestTimeout(1000)  //设置从连接池中获取连接的超时时间
                    .build();
            httpGet.setConfig(requestConfig);
            //添加请求参数
            List<NameValuePair> pairs = new ArrayList<>();
            for(Map.Entry<String,String> entry : map.entrySet()) {
                pairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
            }
            builder.setParameters(pairs);
            //执行GET请求
            response = httpClient.execute(httpGet);
            //解析响应数据
            if(response != null && response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity, "UTF-8");
                //释放资源
                EntityUtils.consume(entity);
            }
            return result;
        } catch (Exception e) {
            log.info("异常信息{}", e.getMessage());
        }
        return result;
    }

    /**
     * POST请求,请求参数为Json格式,可设置Content-Type
     * @param url
     * @param jsonString
     * @param contentType
     * @return java.lang.String
     */
    public static String doPostJson(String url,String jsonString,String contentType) {
        String result = "";
        try {
            //定义返回实例
            CloseableHttpResponse response = null;
            //创建POST请求
            HttpPost httpPost = new HttpPost(url);
            CloseableHttpClient httpClient = HttpClients.createDefault();
            //设置http的链接超时时间
            RequestConfig config = RequestConfig.custom()
                    .setConnectTimeout(60000)    //设置连接超时时间
                    .setSocketTimeout(60000)   //设置响应超时时间
                    .setConnectionRequestTimeout(1000)  //设置从连接池中获取连接的超时时间
                    .build();   //设置响应超时时间
            httpPost.setConfig(config);
            //设置请求头
            if(StringUtils.isEmpty(contentType)){
                httpPost.setHeader("Content-Type","application/json");
            }else{
                httpPost.setHeader("Content-Type",contentType);
            }
            //添加请求参数
            httpPost.setEntity(new ByteArrayEntity(jsonString.getBytes("UTF-8")));
            //执行POST请求
            response = httpClient.execute(httpPost);
            //解析响应数据
            if(response != null && response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity, "UTF-8");
                //释放资源
                EntityUtils.consume(entity);
            }
            return result;
        } catch (Exception e) {
            log.info("异常信息{}", e.getMessage());
        }
        return result;
    }

    /**
     * POST请求,参数格式:form-data
     * @param url
     * @param formData
     * @return java.lang.String
     */
    public static String doPostFormData(String url,Map<String, Object> formData){
        String result = "";
        try {
            //定义返回实例
            CloseableHttpResponse response = null;
            //创建POST请求
            HttpPost httpPost = new HttpPost(url);
            CloseableHttpClient httpClient = HttpClients.createDefault();
            //设置http的链接超时时间
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(6000).setConnectionRequestTimeout(1000)
                    .setSocketTimeout(6000).build();
            httpPost.setConfig(requestConfig);
            //创建参数列表
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            if (formData != null) {
                for (String key : formData.keySet()) {
                    if (formData.get(key) instanceof MultipartFile) {
                        MultipartFile multipartFile = (MultipartFile) formData.get(key);
                        multipartEntityBuilder.addBinaryBody(key, multipartFile.getInputStream(), ContentType.MULTIPART_FORM_DATA, multipartFile.getOriginalFilename());
                    } else {
                        multipartEntityBuilder.addTextBody(key, (String) formData.get(key),ContentType.APPLICATION_JSON);
                    }
                }
            }
            //添加请求参数
            httpPost.setEntity(multipartEntityBuilder.build());
            //执行POST请求
            response = httpClient.execute(httpPost);

            if (response != null && response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity, "UTF-8");
                //释放资源
                EntityUtils.consume(entity);
            }
        } catch (Exception e) {
            log.info("异常信息{}", e.getMessage());
        }
        return result;
    }


}

`