封装apache http

封装apache http

代码如下:
package com.mmkt.publicity.util;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * @author th
 * @date 2022/3/23 10:10
 * @Description:
 */
public class HttpUtil {

    private static Logger log= LoggerFactory.getLogger(HttpUtil.class);


    /**
     * 发送get请求
     */
    public static String sendGet(String url) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String result = "";
        try {
            // 通过址默认配置创建一个httpClient实例
            httpClient = HttpClients.createDefault();
            // 创建httpGet远程连接实例
            HttpGet httpGet = new HttpGet(url);

            // 设置配置请求参数
            RequestConfig requestConfig = getRequestConfig();
            // 为httpGet实例设置配置
            httpGet.setConfig(requestConfig);
            // 执行get请求得到返回对象
            response = httpClient.execute(httpGet);
            // 通过返回对象获取返回数据
            HttpEntity entity = response.getEntity();
            // 通过EntityUtils中的toString方法将结果转换为字符串
            result = EntityUtils.toString(entity);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【远程调用接口异常!!!】");
        }
        finally {
            // 关闭资源
            closeResource(response, httpClient);
        }
        return result;
    }

    /**
     * 发送post请求  form表单提交
     */
    public static String sendformPost(List<NameValuePair> params, String url) {
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建httppost
        HttpPost httpPost = new HttpPost( url);
        String json = null;
        try {
            // 设置提交方式
            httpPost.addHeader("Content-type", "application/x-www-form-urlencoded;charset=UTF-8");
            //设置超时时间
            RequestConfig requestConfig = getRequestConfig();
            httpPost.setConfig(requestConfig);
            httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
            Date startTime = new Date();
            // 执行http请求
            response = httpClient.execute(httpPost);
            // 获得http响应体
            HttpEntity entity = response.getEntity();
            JSONObject jsonObject = JSON.parseObject(EntityUtils.toString(entity, "UTF-8"));
            json = jsonObject.getString("data");
            Date endTime = new Date();
            log.info("【时间戳】:{}-{} , 【时间差】:{}毫秒",  startTime.getTime(), endTime.getTime(), endTime.getTime() - startTime.getTime());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【远程调用接口异常!!!】");
        }finally {
            // 关闭资源
            closeResource(response, httpClient);
        }
        return json;
    }

    /**
     * 发送post请求  body请求
     */
    public static String sendBodyPost(String url, JSONObject paramMap) {

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        HttpPost post = new HttpPost(url);
        String result = "";
        try (CloseableHttpClient closeableHttpClient = httpClientBuilder.build()) {
            // HttpEntity entity = new StringEntity(jsonStrData);
            // 修复 POST json 导致中文乱码
            HttpEntity entity = new StringEntity(paramMap.toString(), "UTF-8");
            post.setEntity(entity);
            post.setHeader("Content-type", "application/json");
            HttpResponse resp = closeableHttpClient.execute(post);
            try {
                InputStream respIs = resp.getEntity().getContent();
                byte[] respBytes = IOUtils.toByteArray(respIs);
                result = new String(respBytes, Charset.forName("UTF-8"));
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            log.error("【远程调用接口异常!!!】");
        }
        return result;
    }

    public static List<NameValuePair> getNameValuePairList(Map<String, Object> map) {
        // 添加参数
        List<NameValuePair> nameValuePairList = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(map)) {
            // 将mapdata中的key存在set集合中,通过迭代器取出所有的key,再获取每一个键对应的值
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                nameValuePairList.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }
        }
        return nameValuePairList;
    }
    /**
     * 关闭资源
     */
    private static void closeResource(CloseableHttpResponse response, CloseableHttpClient httpClient) {
        if (null != response) {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null != httpClient) {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 设置超时时间
     */
    private static RequestConfig getRequestConfig() {
        return RequestConfig.custom()
                        .setSocketTimeout(5000)
                        .setConnectTimeout(5000)
                        .setConnectionRequestTimeout(5000).build();
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值