java HttpClient工具类

此HttpClient工具类包含GET请求,Post JSON为参数请求以及Post表单参数请求。

以下是工具类代码:

package com.yangshaobin.util;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author YSB
 * @Description
 * @date 2023/06/09 10:43
 **/
public class HttpClientUtil {

    private static HttpClient httpClient;

    static {
        httpClient = HttpClientBuilder.create().build();
    }

    /**
     * @param httpGet HttpGet
     * @return HttpResponse
     * @throws Exception
     */
    public static HttpResponse executeGet(HttpGet httpGet) throws Exception {
        try {
            return httpClient.execute(httpGet);
        } catch (Exception e) {
            throw e;
        } finally {
            if (httpGet != null) {
                httpGet.releaseConnection();
            }
        }
    }

    /**
     * @param url    请求路径
     * @param params 请求参数
     * @param header 请求header参数
     * @return 响应结果数据
     * @throws Exception
     */
    public static String executeGet(String url, Map<String, String> params, Map<String, String> header) throws Exception {
        String body;
        try {
            HttpResponse response = executeGetResponse(url, params, header);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                throw new RuntimeException("请求失败");
            } else {
                body = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            throw e;
        }
        return body;
    }

    /**
     * @param url    请求路径
     * @param params 请求参数
     * @param header 请求header参数
     * @return 响应体全部信息
     * @throws Exception
     */
    public static HttpResponse executeGetResponse(String url, Map<String, String> params, Map<String, String> header) throws Exception {
        HttpResponse httpResponse;
        try {
            List<String> mapList = new ArrayList<>();
            if (params != null) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    mapList.add(entry.getKey() + "=" + entry.getValue());
                }
            }
            if (CollectionUtils.isNotEmpty(mapList)) {
                url = url + "?";
                String paramsStr = StringUtils.join(mapList, "&");
                url = url + paramsStr;
            }
            HttpGet httpGet = new HttpGet(url);
            httpGet.setHeader("Content-type", "application/json; charset=utf-8");
            if (header != null) {
                for (Map.Entry<String, String> entry : header.entrySet()) {
                    httpGet.setHeader(entry.getKey(), entry.getValue());
                }
            }
            httpResponse = executeGet(httpGet);
        } catch (Exception e) {
            throw e;
        }
        return httpResponse;
    }

    /**
     * @param httpPost 请求HttpPost
     * @return 响应全部信息
     * @throws Exception
     */
    public static HttpResponse executePost(HttpPost httpPost) throws Exception {
        try {
            return httpClient.execute(httpPost);
        } catch (Exception e) {
            throw e;
        } finally {
            if (httpPost != null) {
                httpPost.releaseConnection();
            }
        }
    }

    /**
     * @param url       请求路径
     * @param jsonParam 请求参数json字符串
     * @param header    请求header参数
     * @return 请求响应内容
     * @throws IOException
     */
    public static String executePostJson(String url, String jsonParam, Map<String, String> header) throws Exception {
        String body;
        try {
            HttpResponse response = executePostJsonResponse(url, jsonParam, header);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                throw new RuntimeException("网络请求失败");
            } else {
                body = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            throw e;
        }
        return body;
    }

    /**
     * @param url       请求路径
     * @param jsonParam 请求参数json字符串
     * @param header    请求header参数
     * @return 请求响应全部内容
     * @throws IOException
     */
    public static HttpResponse executePostJsonResponse(String url, String jsonParam, Map<String, String> header) throws Exception {
        HttpResponse response;
        try {
            HttpPost httpPost = new HttpPost(url);
            if (header != null) {
                for (Map.Entry<String, String> entry : header.entrySet()) {
                    httpPost.setHeader(entry.getKey(), entry.getValue());
                }
            }
            StringEntity entity = new StringEntity(jsonParam, Charset.forName("UTF-8"));
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            response = executePost(httpPost);
        } catch (Exception e) {
            throw e;
        }
        return response;
    }


    /**
     * @param url    请求路径
     * @param params 请求参数
     * @param header 请求header参数
     * @return 请求响应内容
     * @throws Exception
     */
    public static String executePostForm(String url, Map<String, String> params, Map<String, String> header) throws Exception {
        String body;
        try {
            HttpResponse response = executePostFormResponse(url, params, header);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                throw new RuntimeException("请求失败");
            } else {
                body = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            throw e;
        }
        return body;
    }

    /**
     * @param url    请求路径
     * @param params 请求参数
     * @param header 请求header参数
     * @return 请求响应全部内容
     * @throws Exception
     */
    public static HttpResponse executePostFormResponse(String url, Map<String, String> params, Map<String, String> header) throws Exception {
        HttpResponse response;
        try {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
            if (header != null) {
                for (Map.Entry<String, String> entry : header.entrySet()) {
                    httpPost.setHeader(entry.getKey(), entry.getValue());
                }
            }
            List<NameValuePair> nvps = new ArrayList<>();
            if (params != null) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            response = executePost(httpPost);
        } catch (Exception e) {
            throw e;
        }
        return response;
    }


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值