自学内容网 自学内容网

HttpUtil工具

http工具

用到的依赖

<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.13</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.13</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.11.0</version>
        </dependency>

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<String, String> 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<String, String> elem = (Map.Entry<String, String>) 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<String, Object> params, Map<String, String> 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<String, String> elem = (Map.Entry<String, String>) 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;
    }


}


原文地址:https://blog.csdn.net/u011628753/article/details/140384410

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!