HTTP/HTTPS POST 请求工具类
<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>
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;
public class HttpUtils {
private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);
public static final int RETRY_COUNT = 3;
public static String doPost(String requestBody) {
log.info("request body:{}", requestBody);
int count = 0;
HttpResponse httpResponse = null;
do {
try {
httpResponse = doPost("http://127.0.0.1:8859", requestBody);
} catch (Exception e) {
log.error("Request error", e);
try {
Thread.sleep(2 * 1000L);
} catch (InterruptedException interruptedException) {
log.error("", interruptedException);
}
}
count++;
} while (httpResponse == null && count <= RETRY_COUNT);
return parseString(httpResponse);
}
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);
}
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;
}
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();
}
}