简单http请求工具类

13 篇文章 0 订阅
@Slf4j
public class HttpUtils {
    public static final String UTF_8 = "UTF-8";


    /**
     * 发送post请求
     *
     * @return java.lang.String
     * @Date 14:26 2019-04-29
     * @Param [url, paramMap, data, headersMap]
     **/
    public static String sendPost(String url, Map<String, String> paramMap, String data, Map<String, String> headersMap) {
        StringEntity reqEntity = new StringEntity(data, UTF_8);
        return sendPost(url, paramMap, reqEntity, headersMap);
    }

    /**
     * 发送post请求
     *
     * @return java.lang.String
     * @Date 14:26 2019-04-29
     * @Param [url, getParamMap, postParamMap, headersMap]
     **/
    public static String sendPost(String url, Map<String, String> getParamMap, Map<String, String> postParamMap, Map<String, String> headersMap) {
        HttpEntity entity = null;
        if (!CollectionUtils.isEmpty(postParamMap)) {
            List<BasicNameValuePair> collect = new ArrayList<>();
            postParamMap.forEach((key, val) -> collect.add(new BasicNameValuePair(key, val)));
            try {
                entity = new UrlEncodedFormEntity(collect, UTF_8);
            } catch (UnsupportedEncodingException e) {
                log.error("sendPost -> e={}",e.getMessage(),e);
            }
        }
        return sendPost(url, getParamMap, entity, headersMap);
    }


    /**
     * 发送post请求
     *
     * @param url
     * @param paramMap
     * @param entity
     * @param headersMap
     * @return
     */
    public static String sendPost(String url, Map<String, String> paramMap, HttpEntity entity, Map<String, String> headersMap) {
        try {
            //url拼接
            url = splicingURL(url, paramMap);
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(entity);
            //请求头
            if (!CollectionUtils.isEmpty(headersMap)) {
                for (Map.Entry<String, String> entry : headersMap.entrySet()) {
                    httpPost.setHeader(entry.getKey(), entry.getValue());
                }
            }
            //发送post请求,接收返回值
            try (CloseableHttpClient httpClient = HttpClients.createDefault();
                 CloseableHttpResponse httpResponse = httpClient.execute(httpPost)) {
                return resultCheck(httpResponse, url);
            }

        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
        return null;
    }

    /**
     * 发送get请求
     *
     * @param url
     * @param params
     * @return
     */
    public static String doGet(String url, Map<String, String> params, Map<String, String> headersMap) {
        HttpGet httpGet;
        try {
            //设置参数
            url = splicingURL(url, params);
            httpGet = new HttpGet(url);
            //请求头
            if (!CollectionUtils.isEmpty(headersMap)) {
                for (Map.Entry<String, String> entry : headersMap.entrySet()) {
                    httpGet.setHeader(entry.getKey(), entry.getValue());
                }
            }
            log.info("----httpGet:" + httpGet.toString() + " ! ---");
            try (CloseableHttpClient httpClient = HttpClients.createDefault();
                 CloseableHttpResponse response = httpClient.execute(httpGet)) {

                log.info("----response:" + response.toString() + " ! ---");
                return resultCheck(response, url);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return null;
    }


    /**
     * url拼接
     *
     * @param url
     * @param paramMap
     * @return
     */
    private static String splicingURL(String url, Map<String, String> paramMap) {
        try {
            //url拼接
            if (!paramMap.isEmpty()) {
                StringBuilder paramBuilder = new StringBuilder();
                paramBuilder.append(url);
                paramBuilder.append("?");
                for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                    paramBuilder.append(entry.getKey());
                    paramBuilder.append("=");
                    paramBuilder.append(URLEncoder.encode(entry.getValue(), UTF_8));
                    paramBuilder.append("&");
                }
                url = paramBuilder.toString().substring(0, paramBuilder.length() - 1);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return url;
    }


    /**
     * 返回值校验
     *
     * @param response
     * @param url
     * @return
     * @throws Exception
     */
    private static String resultCheck(CloseableHttpResponse response, String url) throws Exception {
        if (null == response) {
            return null;
        }
        int statusCode = response.getStatusLine().getStatusCode();
        //状态值非200
        if (statusCode != HttpStatus.SC_OK) {
            EntityUtils.consume(response.getEntity());
            throw new Exception("Do post request to :" + url + ", statusCode:" + statusCode);
        }
        //返回值
        HttpEntity respEntity = response.getEntity();
        if (respEntity == null) {
            throw new Exception("Do post request to :" + url + ", response entity is empty.");
        }

        return EntityUtils.toString(respEntity);
    }

}

maven引入http jar包

        <!--  引入http      -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.10</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.6</version>
        </dependency>

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值