HttpUtil工具

07-14 1002阅读

http工具

用到的依赖

HttpUtil工具
(图片来源网络,侵删)
            org.apache.httpcomponents
            httpclient
            4.5.13
        
        
            org.apache.httpcomponents
            httpmime
            4.5.13
        
        
            commons-io
            commons-io
            2.11.0
        

httpUtil工具

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.client.utils.HttpClientUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;
/**
 * http请求工具类
 */
public class HttpUtil {
    private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
    private static PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager();
    private static RequestConfig requestConfig;
    private static final String DEFAULT_CHARSET = "UTF-8";
    public HttpUtil() {
    }
    static {
        connMgr.setMaxTotal(100);
        connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());
        RequestConfig.Builder configBuilder = RequestConfig.custom();
        configBuilder.setConnectTimeout(5000);
        configBuilder.setSocketTimeout(20000);
        configBuilder.setConnectionRequestTimeout(5000);
        requestConfig = configBuilder.build();
    }
    /**
     * Post方式
     *
     * @param apiUrl
     * @param json      json数据
     * @param headerMap 请求头
     * @return
     */
    public static String doPost(String apiUrl, String json, Map headerMap) throws Exception {
        long start = System.currentTimeMillis();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String httpStr = null;
        HttpPost httpPost = new HttpPost(apiUrl);
        CloseableHttpResponse response = null;
        int statusCode = -999;
        try {
            httpPost.setConfig(requestConfig);
            StringEntity stringEntity = new StringEntity(json.toString(), DEFAULT_CHARSET);
            stringEntity.setContentEncoding(DEFAULT_CHARSET);
            //循环增加header
            if (headerMap != null) {
                Iterator headerIterator = headerMap.entrySet().iterator();
                while (headerIterator.hasNext()) {
                    Map.Entry elem = (Map.Entry) headerIterator.next();
                    httpPost.addHeader(elem.getKey(), elem.getValue());
                }
            }
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            statusCode = response.getStatusLine().getStatusCode();
            httpStr = EntityUtils.toString(entity, DEFAULT_CHARSET);
        } catch (Exception e) {
            logger.error("HttpUtil发生错误:", e);
            throw new Exception("网络异常", e);
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException var19) {
                    var19.printStackTrace();
                }
            }
            logger.info("request to:{},param:{},response code:{},result:{},cost {} ms", new Object[]{apiUrl, json, statusCode, httpStr, System.currentTimeMillis() - start});
        }
        return httpStr;
    }
    /**
     * 请求方式 Get
     *
     * @param url       请求链接
     * @param params    以 x-www-form-urlencoded
     * @param headerMap 请求头参数
     * @return
     */
    public static String doGet(String url, Map params, Map headerMap) throws Exception {
        long start = System.currentTimeMillis();
        StringBuffer param = new StringBuffer();
        if (null != params) {
            int i = 0;
            for (Iterator iterator = params.keySet().iterator(); iterator.hasNext(); ++i) {
                String key = (String) iterator.next();
                if (i == 0) {
                    param.append("?");
                } else {
                    param.append("&");
                }
                param.append(key).append("=").append(params.get(key));
            }
        }
        String apiUrl = url + param;
        String result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        int statusCode = -999;
        try {
            HttpGet httpGet = new HttpGet(apiUrl);
            //循环增加header
            if (headerMap != null) {
                Iterator headerIterator = headerMap.entrySet().iterator();
                while (headerIterator.hasNext()) {
                    Map.Entry elem = (Map.Entry) headerIterator.next();
                    httpGet.addHeader(elem.getKey(), elem.getValue());
                }
            }
            HttpResponse response = httpClient.execute(httpGet);
            statusCode = response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();
                result = IOUtils.toString(instream, DEFAULT_CHARSET);
            }
        } catch (Exception e) {
            logger.error("HttpUtil发生错误:", e);
            throw new Exception("网络异常", e);
        } finally {
            if (httpClient != null) {
                HttpClientUtils.closeQuietly(httpClient);
            }
            logger.info("request to:{},param:{},response code:{},result:{},cost {} ms", new Object[]{apiUrl, param.toString(), statusCode, result, System.currentTimeMillis() - start});
        }
        return result;
    }
}
VPS购买请点击我

文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。

目录[+]