简单http请求工具类

@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 paramMap, String data, Map 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 getParamMap, Map postParamMap, Map headersMap) {
        HttpEntity entity = null;
        if (!CollectionUtils.isEmpty(postParamMap)) {
            List 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 paramMap, HttpEntity entity, Map headersMap) {
        try {
            //url拼接
            url = splicingURL(url, paramMap);
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(entity);
            //请求头
            if (!CollectionUtils.isEmpty(headersMap)) {
                for (Map.Entry 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 params, Map headersMap) {
        HttpGet httpGet;
        try {
            //设置参数
            url = splicingURL(url, params);
            httpGet = new HttpGet(url);
            //请求头
            if (!CollectionUtils.isEmpty(headersMap)) {
                for (Map.Entry 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 paramMap) {
        try {
            //url拼接
            if (!paramMap.isEmpty()) {
                StringBuilder paramBuilder = new StringBuilder();
                paramBuilder.append(url);
                paramBuilder.append("?");
                for (Map.Entry 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包

        
        
            org.apache.httpcomponents
            httpcore
            4.4.10
        
        
            org.apache.httpcomponents
            httpclient
            4.5.6
        

 

你可能感兴趣的:(web,java)