zoukankan      html  css  js  c++  java
  • HttpUtil



    import com.google.common.util.concurrent.RateLimiter;

    import org.apache.commons.collections.MapUtils;
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.HttpException;
    import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
    import org.apache.commons.httpclient.methods.GetMethod;
    import org.apache.commons.httpclient.methods.PostMethod;
    import org.apache.commons.lang3.StringUtils;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.util.EntityUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;

    import java.io.IOException;
    import java.util.Map;
    import java.util.Set;
    import java.util.concurrent.TimeUnit;

    /**
    * http请求工具类
    */
    public class HttpUtil {
    private final static Logger LOGGER = LoggerFactory.getLogger(HttpUtil.class);

    private static final String URL_PARAM_CONNECT_EQUAL_SIGN = "=";
    private static final String URL_PARAM_CONNECT_FLAG = "&";
    private static final String HTTP_CONTENT_TYPE_KEY = "ContentType";

    private static MultiThreadedHttpConnectionManager connectionManager = null;
    /**
    * 连接超时时间
    */
    private static int connectionTimeOut = 2000;
    /**
    * 响应超时时间
    */
    private static int socketTimeOut = 2000;
    /**
    * 最大连接数
    */
    private static int maxConnectionPerHost = 30;
    /**
    * 最大活动连接数
    */
    private static int maxTotalConnections = 30;

    private static HttpClient client;
    private static CloseableHttpClient closeableHttpClient;

    /**
    * 令牌桶限流
    * 每秒产生300个令牌
    */
    private static RateLimiter rateLimiter = RateLimiter.create(300);

    static {
    connectionManager = new MultiThreadedHttpConnectionManager();
    connectionManager.getParams().setConnectionTimeout(connectionTimeOut);
    connectionManager.getParams().setSoTimeout(socketTimeOut);
    connectionManager.getParams().setDefaultMaxConnectionsPerHost(maxConnectionPerHost);
    connectionManager.getParams().setMaxTotalConnections(maxTotalConnections);
    client = new HttpClient(connectionManager);
    closeableHttpClient = HttpClients.createDefault();
    }

    /**
    * POST方式提交数据
    *
    * @param url 待请求的URL
    * @param params 要提交的数据
    * @return 响应结果
    */
    public static HttpResult doPost(String url, Map<String, String> params) {
    //1秒没有获取令牌则 拒绝访问
    if (!rateLimiter.tryAcquire(1, TimeUnit.SECONDS)) {
    throw new BusinessException(ErrorStatus.GET_LIMIT_TOKEN_FAIL_ERROR);
    }

    HttpResult result = new HttpResult();
    PostMethod postMethod = null;
    try {
    postMethod = new PostMethod(url);
    if (StringUtils.isEmpty(params.get(HTTP_CONTENT_TYPE_KEY))) {
    postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF8");
    }

    if (MapUtils.isNotEmpty(params)) {
    Set<Map.Entry<String, String>> entries = params.entrySet();
    for (Map.Entry<String, String> entry : entries) {
    postMethod.addParameter(entry.getKey(), entry.getValue());
    }
    }

    client.executeMethod(postMethod);
    result.setStatusCode(postMethod.getStatusCode());
    result.setData(postMethod.getResponseBodyAsString());
    } catch (HttpException e) {
    LOGGER.error("发生致命的异常,可能是协议不对或者返回的内容有问题", e);
    } catch (IOException e) {
    LOGGER.error("发生网络异常", e);
    } finally {
    if (postMethod != null) {
    postMethod.releaseConnection();
    }
    }
    return result;
    }

    /**
    * POST方式提交数据
    *
    * @param url 待请求的URL
    * @return 响应结果
    */
    public static HttpResult doPostJson(String url, String json) {
    //1秒没有获取令牌则 拒绝访问
    if (!rateLimiter.tryAcquire(1, TimeUnit.SECONDS)) {
    throw new BusinessException(ErrorStatus.GET_LIMIT_TOKEN_FAIL_ERROR);
    }

    HttpResult result = new HttpResult();
    HttpPost httpPost = null;
    CloseableHttpResponse response = null;
    try {
    httpPost = new HttpPost(url);
    StringEntity stringEntity = new StringEntity(json);
    stringEntity.setContentEncoding("UTF-8");
    stringEntity.setContentType("application/json");
    httpPost.setEntity(stringEntity);

    response = closeableHttpClient.execute(httpPost);
    result.setStatusCode(response.getStatusLine().getStatusCode());
    result.setData(EntityUtils.toString(response.getEntity(), "utf-8"));
    } catch (HttpException e) {
    LOGGER.error("发生致命的异常,可能是协议不对或者返回的内容有问题", e);
    } catch (IOException e) {
    LOGGER.error("发生网络异常", e);
    } finally {
    if (httpPost != null) {
    httpPost.releaseConnection();
    }
    }
    return result;
    }

    /**
    * GET方式提交数据
    *
    * @param url 待请求的URL
    * @param params 要提交的数据
    * @return 响应结果
    */
    public static HttpResult doGet(String url, Map<String, String> params) {
    //1秒没有获取令牌则 拒绝访问
    if (!rateLimiter.tryAcquire(1, TimeUnit.SECONDS)) {
    throw new BusinessException(ErrorStatus.GET_LIMIT_TOKEN_FAIL_ERROR);
    }

    HttpResult result = new HttpResult();
    GetMethod getMethod = null;

    String httpGetParamsStr = getHttpGetParamsStr(params);
    if (StringUtils.isNotEmpty(httpGetParamsStr)) {
    url = url + "?" + httpGetParamsStr;
    }
    try {
    getMethod = new GetMethod(url);
    if (StringUtils.isEmpty(params.get(HTTP_CONTENT_TYPE_KEY))) {
    getMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF8");
    }

    client.executeMethod(getMethod);
    result.setStatusCode(getMethod.getStatusCode());
    result.setData(getMethod.getResponseBodyAsString());
    } catch (HttpException e) {
    LOGGER.error("发生致命的异常,可能是协议不对或者返回的内容有问题", e);
    } catch (IOException e) {
    LOGGER.error("发生网络异常", e);
    } finally {
    if (getMethod != null) {
    getMethod.releaseConnection();
    }
    }

    return result;
    }

    /**
    * 获取get请求参数字符串
    *
    * @param params
    * @return
    */
    private static String getHttpGetParamsStr(Map<String, String> params) {
    if (MapUtils.isEmpty(params)) {
    return null;
    }
    StringBuilder builder = new StringBuilder();
    Set<Map.Entry<String, String>> entries = params.entrySet();
    int i = 0;
    for (Map.Entry<String, String> entry : entries) {
    builder.append(entry.getKey()).append(URL_PARAM_CONNECT_EQUAL_SIGN).append(entry.getValue());
    if (i != entries.size() - 1) {
    builder.append(URL_PARAM_CONNECT_FLAG);
    }
    i++;
    }
    return builder.toString();
    }
    }
  • 相关阅读:
    Linux
    bzoj 1834
    bzoj 1002 找规律(基尔霍夫矩阵)
    bzoj 1005 组合数学 Purfer Sequence
    bzoj 1601 最小生成树
    bzoj 1001 平面图转对偶图 最短路求图最小割
    bzoj 1192 二进制
    bzoj 1012 基础线段树
    bzoj 1044 贪心二分+DP
    bzoj 1011 近似估计
  • 原文地址:https://www.cnblogs.com/zfzf1/p/10869067.html
Copyright © 2011-2022 走看看