package com.yung.user.util;

import com.yung.user.dto.HttpResult;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * 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 = 3000;
    /**
     * 响应超时时间
     */
    private static int socketTimeOut = 3000;
    /**
     * 最大连接数
     */
    private static int maxConnectionPerHost = 14;
    /**
     * 最大活动连接数
     */
    private static int maxTotalConnections = 14;

    private static HttpClient client;

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

    /**
     * POST方式提交数据
     * @param url    待请求的URL
     * @param params 要提交的数据
     * @return 响应结果
     */
    public static HttpResult doPost(String url, Map<String, String> params) {
        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;
    }


    /**
     * GET方式提交数据
     * @param url    待请求的URL
     * @param params 要提交的数据
     * @return 响应结果
     */
    public static HttpResult doGet(String url, Map<String, String> params) {
        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();
    }
}
package com.yung.user.dto;

/**
 * HttpUtil的返回值
 */
public class HttpResult {
    private Integer statusCode;
    private String data;

    public Integer getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(Integer statusCode) {
        this.statusCode = statusCode;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "HttpResult{" +
                "statusCode=" + statusCode +
                ", data='" + data + '\'' +
                '}';
    }
}

 

package com.yung.user.util;

import com.yung.user.dto.HttpResult;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
* 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 = 3000;
/**
* 响应超时时间
*/
private static int socketTimeOut = 3000;
/**
* 最大连接数
*/
private static int maxConnectionPerHost = 14;
/**
* 最大活动连接数
*/
private static int maxTotalConnections = 14;

private static HttpClient client;

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

/**
* POST方式提交数据
* @param url 待请求的URL
* @param params 要提交的数据
* @return 响应结果
*/
public static HttpResult doPost(String url, Map<String, String> params) {
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;
}


/**
* GET方式提交数据
* @param url 待请求的URL
* @param params 要提交的数据
* @return 响应结果
*/
public static HttpResult doGet(String url, Map<String, String> params) {
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();
}
}
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。