Http请求工具类

<!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient -->
<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
</dependency>
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * http请求工具类
 *
 * @author 
 * @date 2021/7/26 11:15
 */
public class HttpUtil {

    private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    /**
     * 读取超时
     */
    private final static int SOCKET_TIMEOUT = 5000;

    /**
     * 连接超时
     */
    private final static int CONNECTION_TIMEOUT = 30000;

    /**
     * 每个HOST的最大连接数量(连接至目的主机的线程数)
     */
    private final static int MAX_CONN_PRE_HOST = 2;
    
    /**
     * 连接池的最大连接数(相当于线程数)
     */
    private final static int MAX_CONN = 2;

    /**
     * 连接设置
     *
     * @return httpConnectionManager
     */
    private static HttpConnectionManager getHttpConnectionManager() {
        HttpConnectionManager httpConnectionManager = new MultiThreadedHttpConnectionManager();
        HttpConnectionManagerParams params = httpConnectionManager.getParams();
        params.setConnectionTimeout(CONNECTION_TIMEOUT);
        params.setSoTimeout(SOCKET_TIMEOUT);
        params.setDefaultMaxConnectionsPerHost(MAX_CONN_PRE_HOST);
        params.setMaxTotalConnections(MAX_CONN);
        return httpConnectionManager;
    }

    public static HttpResult get(String url) {
        HttpResult result = new HttpResult();

        HttpClient httpClient = new HttpClient(getHttpConnectionManager());

        logger.info("请求路径:{}", url);
        GetMethod getMethod = new GetMethod(url);
        try {
            getMethod.addRequestHeader("Content-Type", "text/html; charset=UTF-8");
            getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
            getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));

            int httpState = httpClient.executeMethod(getMethod);
            handleRespInfo(result, getMethod.getResponseBody(), getMethod.getResponseCharSet(), httpState, getMethod.getStatusLine());
        } catch (Exception e) {
            result.setCode(500);
            result.setMessage(e.getMessage());
            logger.error("请求异常:", e);
        } finally {
            getMethod.releaseConnection();
        }
        return result;
    }

    public static HttpResult post(String url, String jsonParam) {
        HttpResult result = new HttpResult();

        HttpClient httpClient = new HttpClient(getHttpConnectionManager());
        logger.info("请求路径:{}", url);
        PostMethod postMethod = new PostMethod(url);
        try {
            postMethod.setRequestHeader("Content-Type", "application/json;charset=utf-8");
            postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
            postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));
            if (StringUtils.isNotBlank(jsonParam)) {
                logger.info("请求报文:{}", jsonParam);
                postMethod.setRequestEntity(new StringRequestEntity(jsonParam, "application/json", "utf-8"));
            }
            int httpState = httpClient.executeMethod(postMethod);
            handleRespInfo(result, postMethod.getResponseBody(), postMethod.getResponseCharSet(), httpState, postMethod.getStatusLine());
        } catch (Exception e) {
            result.setCode(500);
            result.setMessage(e.getMessage());
            logger.error("请求异常:", e);
        } finally {
            postMethod.releaseConnection();
        }

        return result;
    }

    private static void handleRespInfo(HttpResult result, byte[] responseBody, String responseCharSet,
                                       int statusCode, StatusLine statusLine) throws IOException {
        String respInfo = new String(responseBody, responseCharSet);
        logger.info("响应报文:{}", respInfo);

        result.setCode(statusCode);
        if (statusCode == HttpStatus.SC_OK) {
            result.setData(respInfo);
            logger.info("请求成功");
        } else {
            result.setMessage(statusLine.toString());
            logger.info("请求失败:{}", statusLine.toString());
        }
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值