HTTP POST 请求工具类

HTTP/HTTPS POST 请求工具类

  • Maven pom.xml 引入依赖
<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.5.13</version>
</dependency>
<dependency>
	<groupId>org.apache.commons</groupId>
	<artifactId>commons-lang3</artifactId>
	<version>3.12.0</version>
</dependency>
  • Java 工具类
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author former Road
 * @Description HTTP request Utility
 * @date 2022/8/8 08:08
 */
public class HttpUtils {

    private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * Number of HTTP request retries(Please adjust by yourself)
     * HTTP请求重试次数(请自行调整)
     */
    public static final int RETRY_COUNT = 3;

    /**
     * POST request with retry mechanism
     * 带重试机制的POST请求
     *
     * @param requestBody 请求消息体
     * @return
     */
    public static String doPost(String requestBody) {
        // Logging the request message body - 日志记录请求消息体
        log.info("request body:{}", requestBody);
        int count = 0;
        HttpResponse httpResponse = null;
        do {
            try {
                // TODO Replace with the actual request address - 替换成实际的接口请求地址
                httpResponse = doPost("http://127.0.0.1:8859", requestBody);
            } catch (Exception e) {
                // Recording Exception Logs - 记录异常日志
                log.error("Request error", e);
                try {
                    // Adjust the interval between retry requests - 自行调整重试请求的间隔时间
                    Thread.sleep(2 * 1000L);
                } catch (InterruptedException interruptedException) {
                    log.error("", interruptedException);
                }
            }
            count++;
        } while (httpResponse == null && count <= RETRY_COUNT);
        return parseString(httpResponse);
    }


    /**
     * Execute the POST request
     * 执行POST请求
     *
     * @param host 请求地址
     * @param body 请求消息体
     * @return HttpResponse
     * @throws Exception
     */
    public static HttpResponse doPost(String host, String body)
            throws Exception {
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost request = new HttpPost(host);
        if (StringUtils.isNotBlank(body)) {
            request.setEntity(new StringEntity(body, StandardCharsets.UTF_8.name()));
        }
        request.setConfig(setTimeOutConfig(request.getConfig()));
        return httpClient.execute(request);
    }

    /**
     * Converts the result of the request to a string
     * 将结果转换成字符串
     *
     * @param httpResponse http 请求响应
     * @return String
     */
    public static String parseString(HttpResponse httpResponse) {
        if (httpResponse == null) {
            return null;
        }
        HttpEntity entity = httpResponse.getEntity();
        String resp = null;
        try {
            resp = EntityUtils.toString(entity, StandardCharsets.UTF_8.name());
            EntityUtils.consume(entity);
        } catch (IOException e) {
            log.error("Upstream response message error", e);
        }
        return resp;
    }

    /**
     * Set connection timeout, request timeout, and read timeout milliseconds
     * 设置 连接超时、 请求超时 、 读取超时时间  毫秒
     *
     * @param requestConfig request configuration items
     * @return RequestConfig
     */
    private static RequestConfig setTimeOutConfig(RequestConfig requestConfig) {
        if (requestConfig == null) {
            requestConfig = RequestConfig.DEFAULT;
        }
        return RequestConfig.copy(requestConfig)
                .setConnectionRequestTimeout(10 * 1000)
                .setConnectTimeout(10 * 1000)
                .setSocketTimeout(10 * 1000)
                .build();
    }

}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值