com.github.cosycode.ext.web.http.HttpUtils Maven / Gradle / Ivy
Show all versions of extend-mod Show documentation
package com.github.cosycode.ext.web.http;
import com.github.cosycode.ext.se.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.hc.client5.http.ClientProtocolException;
import org.apache.hc.client5.http.HttpResponseException;
import org.apache.hc.client5.http.classic.methods.*;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.core5.annotation.Contract;
import org.apache.hc.core5.annotation.ThreadingBehavior;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.HttpClientResponseHandler;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.message.BasicHeader;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
/**
* Description : the tool class for http call, based on HttpClient5, more pure.
*
* created in 2022/12
*
* @author CPF
**/
@Slf4j
public class HttpUtils {
private HttpUtils() {
}
private static String createRequestUrl(String url, Map paramMap) {
// convert request params from Map params to List param
if (paramMap != null && !paramMap.isEmpty()) {
List paramList = new ArrayList<>();
for (Map.Entry stringEntry : paramMap.entrySet()) {
paramList.add(new BasicNameValuePair(stringEntry.getKey(), stringEntry.getValue()));
}
String paramString = paramList.stream().map(it -> it.getName() + "=" + it.getValue()).collect(Collectors.joining("&"));
if (url.contains("?")) {
return url + "&" + paramString;
} else {
return url + "?" + paramString;
}
} else {
return url;
}
}
public static T http(String method, String requestUrl, Map headers, Map params,
Object jsonBody, HttpClientResponseHandler extends T> responseHandler) throws IOException {
return http(Http5ClientConfig.getCloseableHttpClient(), method, requestUrl, headers, params, jsonBody, responseHandler);
}
public static T http(CloseableHttpClient httpClient, String method, String requestUrl, Map headers, Map params,
Object jsonBody, HttpClientResponseHandler extends T> responseHandler) throws IOException {
// engage url
String url = createRequestUrl(requestUrl, params);
// create HttpUriRequestBase Object
HttpUriRequestBase httpUriRequestBase = new HttpUriRequestBase(method, URI.create(url));
// Convert style from Map headers to List
if (headers != null && !headers.isEmpty()) {
for (Map.Entry objectEntry : headers.entrySet()) {
httpUriRequestBase.addHeader(new BasicHeader(objectEntry.getKey(), objectEntry.getValue()));
}
}
// setting body
String payload = "";
if (jsonBody != null) {
payload = jsonBody instanceof String ? (String) jsonBody : JsonUtils.toJson(jsonBody);
httpUriRequestBase.setEntity(new StringEntity(payload, StandardCharsets.UTF_8));
}
String uuid = UUID.randomUUID().toString().substring(0, 9) + Thread.currentThread().getId();
T execute = null;
try {
log.info("{} [HTTP Req ] [{}] {}\n{}", uuid, method, url, payload);
// 调用 HttpClient 的 execute 方法执行请求
execute = httpClient.execute(httpUriRequestBase, responseHandler);
} catch (Exception e) {
log.error("{} [HTTP Error ] [{}] {}\n{}", uuid, method, url, payload);
throw e;
} finally {
log.info("{} [HTTP Resp] [{}] \n {}", uuid, method, execute);
}
return execute;
}
public static MyHttpResponse get(String urlString, Map headers, Map params) throws IOException {
return http(HttpGet.METHOD_NAME, urlString, headers, params, null, MyHttpResponse.DEFAULT_HANDLER);
}
public static MyHttpResponse post(String urlString, Map headers, Map params, Object jsonBody) throws IOException {
return http(HttpPost.METHOD_NAME, urlString, headers, params, jsonBody, MyHttpResponse.DEFAULT_HANDLER);
}
public static MyHttpResponse put(String urlString, Map headers, Map params, Object jsonBody) throws IOException {
return http(HttpPut.METHOD_NAME, urlString, headers, params, jsonBody, MyHttpResponse.DEFAULT_HANDLER);
}
public static MyHttpResponse delete(String urlString, Map headers, Map params, Object jsonBody) throws IOException {
return http(HttpDelete.METHOD_NAME, urlString, headers, params, jsonBody, MyHttpResponse.DEFAULT_HANDLER);
}
@Contract(threading = ThreadingBehavior.STATELESS)
public static class MyStringHttpClientResponseHandler implements HttpClientResponseHandler {
@Override
public String handleResponse(ClassicHttpResponse response) throws IOException {
HttpEntity entity = response.getEntity();
if (response.getCode() >= 300) {
EntityUtils.consume(entity);
throw new HttpResponseException(response.getCode(), response.getReasonPhrase());
} else {
return entity == null ? null : this.handleEntity(entity);
}
}
public String handleEntity(HttpEntity entity) throws IOException {
try {
return EntityUtils.toString(entity);
} catch (ParseException var3) {
throw new ClientProtocolException(var3);
}
}
}
}