Http请求工具类HttpUtil

package com.test.mingjing.common;

import com.alibaba.fastjson.JSONObject;
import com.helijia.merchant.modules.item.vo.ApplyArtworkGroup;
import com.helijia.merchant.modules.item.web.ItemController;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
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.config.ConnectionConfig;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
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.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.CodingErrorAction;
import java.util.*;

/**
 * @ClasName HttpUtil
 * @description HTTP请求接口
 * @Author: Allen
 * @Create: 2019-03-21 16:07
 */
public class HttpUtil {
    private final static Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    private static final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36";
    // 超时设置
    private static final RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(5000)
            .setConnectionRequestTimeout(5000)
            .setSocketTimeout(10000)
            .build();

    // 编码设置
    private static final ConnectionConfig connectionConfig = ConnectionConfig.custom()
            .setMalformedInputAction(CodingErrorAction.IGNORE)
            .setUnmappableInputAction(CodingErrorAction.IGNORE)
            .setCharset(Consts.UTF_8)
            .build();

    private static HttpClientBuilder getBuilder() {
        List<Header> headers = new ArrayList<>();
        Header header = new BasicHeader("User-Agent", USER_AGENT);
        headers.add(header);
        return HttpClients.custom().setDefaultConnectionConfig(connectionConfig).setDefaultHeaders(headers).setDefaultRequestConfig(requestConfig);
    }

    /**
     * @return java.lang.String
     * @Description GET请求
     * @Author Allen
     * @Date 2019-03-21 17:34
     * @Param [url]
     */
    public static String sendGet(String url) {
        String result = "";
        HttpGet httpGet = new HttpGet(url);
        try (CloseableHttpClient httpclient = getBuilder().build();
             CloseableHttpResponse response = httpclient.execute(httpGet)) {
            HttpEntity httpEntity = response.getEntity();
            result = EntityUtils.toString(httpEntity);
        } catch (IOException e) {
            logger.info(String.format("sendGet error %s", e.getMessage()));
        }
        return result;
    }


    /**
     * @Description 初始化HttpPost,主要是编码格式
     * @Author Allen
     * @Date 2019-03-21 17:41
     * @Param [url, stringEntity]
     * @return org.apache.http.client.methods.HttpPost
     */
    private static void initHttpPost(HttpPost post, StringEntity stringEntity){
        stringEntity.setContentType("application/json");
        stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        post.addHeader("Content-Type", "application/json;charset=utf-8");
        post.setHeader("Accept", "application/json");
        post.setEntity(stringEntity);
    }

    /**
     * @Description 获取HttpPost
     * @Author Allen
     * @Date 2019-03-21 17:52
     * @Param [url, stringEntity]
     * @return org.apache.http.client.methods.HttpPost
     */
    private static HttpPost getHttpPost(String url, StringEntity stringEntity){
        HttpPost httpPost = new HttpPost(url);
        initHttpPost(httpPost, stringEntity);
        return httpPost;
    }

    /**
     * @Description 获取HttpPost
     * @Author Allen
     * @Date 2019-03-21 17:56
     * @Param [url, paramJsonStr:参数数据json格式]
     * @return org.apache.http.client.methods.HttpPost
     */
    private static HttpPost getHttpPost(String url, String paramJsonStr){
        StringEntity stringEntity = new StringEntity(paramJsonStr, Charset.forName("UTF-8"));
        HttpPost httpPost = new HttpPost(url);
        initHttpPost(httpPost, stringEntity);
        return httpPost;
    }

    /**
     * @Description 发送HttpPost请求,参数为json字符串
     * @Author Allen
     * @Date 2019-03-21 17:35
     * @Param [url, jsonStr]
     * @return java.lang.String
     */
    public static String sendPost(String url, String paramJsonStr){
        String result = httpExecute(getHttpPost(url, paramJsonStr));
        return result;
    }

    /**
     * @Description 发送HttpPost请求,参数为json字符串,设置Header体
     * @Author Allen
     * @Date 2019-03-21 17:35
     * @Param [url, jsonStr, headers]
     * @return java.lang.String
     */
    public static String sendPost(String url, String jsonStr, Map<String, String> headers){
        // 设置entity
        logger.info(String.format("请求地址:%s ",url));
        logger.info(String.format("请求参数:%s ",jsonStr));
        StringEntity stringEntity = new StringEntity(jsonStr, Charset.forName("UTF-8"));
        HttpPost httpPost = getHttpPost(url, stringEntity);
        if (headers != null && !headers.isEmpty()) {
            Set<String> keys = headers.keySet();
            for (Iterator<String> i = keys.iterator(); i.hasNext();) {
                String key = (String) i.next();
                httpPost.addHeader(key, headers.get(key));
            }
        }
        String result = httpExecute(httpPost);
        logger.info(String.format("请求结果:%s",result));
        return result;
    }

    /**
     * 发送HttpPost请求,提交表单,支持文件上传
     *
     * @param url    请求地址
     * @param params 表单参数
     * @return
     */
    public static String sendPost(String url, Map<String, String> params, Map<String, String> headers){

        // 设置entity
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setCharset(Charset.forName("UTF-8"));
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        if (MapUtils.isNotEmpty(params)) { // 普通表单参数
            for (String key : params.keySet()) {
                StringBody stringBody = new StringBody(params.get(key), ContentType.create("text/plain", "UTF-8"));
                builder.addPart(key, stringBody);
            }
        }

        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(builder.build());

        httpPost.setHeader("Content-Type", "application/json");
        if (!headers.isEmpty()) {
            Set<String> keys = headers.keySet();
            for (Iterator<String> i = keys.iterator(); i.hasNext(); ) {
                String key = (String) i.next();
                httpPost.addHeader(key, headers.get(key));
            }
        }
        String result = httpExecute(httpPost);
        return result;
    }

    private static String httpExecute(HttpPost httpPost) {
        String result = "";
        try (CloseableHttpClient httpclient = getBuilder().build();
             CloseableHttpResponse httpResponse = httpclient.execute(httpPost)) {
            HttpEntity httpEntity = httpResponse.getEntity();
            result = EntityUtils.toString(httpEntity);
        } catch (IOException e) {
            logger.debug(String.format("---------ERROR ! message:%s",e.getMessage()));
        }
        return result;
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值