Http tool code and format optimization

pull/805/head
chen.ma 2 years ago
parent b74c2db9cc
commit 1acfb98498

@ -65,7 +65,8 @@ public interface JsonFacade {
<T> List<T> parseArray(String text, Class<T> clazz); <T> List<T> parseArray(String text, Class<T> clazz);
/** /**
* validate Json. * Validate json.
*
* @param text * @param text
* @return * @return
*/ */

@ -18,20 +18,29 @@
package cn.hippo4j.common.constant; package cn.hippo4j.common.constant;
/** /**
* header constants. * Http header constants.
*/ */
public interface HttpHeaderConsts { public interface HttpHeaderConstants {
String CLIENT_VERSION_HEADER = "Client-Version"; String CLIENT_VERSION_HEADER = "Client-Version";
String USER_AGENT_HEADER = "User-Agent"; String USER_AGENT_HEADER = "User-Agent";
String REQUEST_SOURCE_HEADER = "Request-Source"; String REQUEST_SOURCE_HEADER = "Request-Source";
String CONTENT_TYPE = "Content-Type"; String CONTENT_TYPE = "Content-Type";
String CONTENT_LENGTH = "Content-Length"; String CONTENT_LENGTH = "Content-Length";
String ACCEPT_CHARSET = "Accept-Charset"; String ACCEPT_CHARSET = "Accept-Charset";
String ACCEPT_ENCODING = "Accept-Encoding"; String ACCEPT_ENCODING = "Accept-Encoding";
String CONTENT_ENCODING = "Content-Encoding"; String CONTENT_ENCODING = "Content-Encoding";
String CONNECTION = "Requester"; String CONNECTION = "Requester";
String REQUEST_ID = "RequestId"; String REQUEST_ID = "RequestId";
String REQUEST_MODULE = "Request-Module";
String REQUEST_MODULE = "Request-Module";
} }

@ -20,7 +20,7 @@ package cn.hippo4j.common.constant;
import cn.hippo4j.common.toolkit.StringUtil; import cn.hippo4j.common.toolkit.StringUtil;
/** /**
* Http Media types. * Http media type.
* *
* @author Rongzhen Yan * @author Rongzhen Yan
*/ */
@ -85,7 +85,7 @@ public final class HttpMediaType {
* Use the given contentType and charset to assemble into a {@code MediaType} object. * Use the given contentType and charset to assemble into a {@code MediaType} object.
* *
* @param contentType contentType * @param contentType contentType
* @param charset charset * @param charset charset
* @return MediaType * @return MediaType
*/ */
public static HttpMediaType valueOf(String contentType, String charset) { public static HttpMediaType valueOf(String contentType, String charset) {

@ -18,50 +18,91 @@
package cn.hippo4j.common.constant; package cn.hippo4j.common.constant;
/** /**
* Http * Http response code.
*
* @author Rongzhen Yan * @author Rongzhen Yan
*/ */
public interface HttpResponseCode { public interface HttpResponseCode {
int SC_CONTINUE = 100; int SC_CONTINUE = 100;
int SC_SWITCHING_PROTOCOLS = 101; int SC_SWITCHING_PROTOCOLS = 101;
int SC_OK = 200; int SC_OK = 200;
int SC_CREATED = 201; int SC_CREATED = 201;
int SC_ACCEPTED = 202; int SC_ACCEPTED = 202;
int SC_NON_AUTHORITATIVE_INFORMATION = 203; int SC_NON_AUTHORITATIVE_INFORMATION = 203;
int SC_NO_CONTENT = 204; int SC_NO_CONTENT = 204;
int SC_RESET_CONTENT = 205; int SC_RESET_CONTENT = 205;
int SC_PARTIAL_CONTENT = 206; int SC_PARTIAL_CONTENT = 206;
int SC_MULTIPLE_CHOICES = 300; int SC_MULTIPLE_CHOICES = 300;
int SC_MOVED_PERMANENTLY = 301; int SC_MOVED_PERMANENTLY = 301;
int SC_MOVED_TEMPORARILY = 302; int SC_MOVED_TEMPORARILY = 302;
int SC_FOUND = 302; int SC_FOUND = 302;
int SC_SEE_OTHER = 303; int SC_SEE_OTHER = 303;
int SC_NOT_MODIFIED = 304; int SC_NOT_MODIFIED = 304;
int SC_USE_PROXY = 305; int SC_USE_PROXY = 305;
int SC_TEMPORARY_REDIRECT = 307; int SC_TEMPORARY_REDIRECT = 307;
int SC_BAD_REQUEST = 400; int SC_BAD_REQUEST = 400;
int SC_UNAUTHORIZED = 401; int SC_UNAUTHORIZED = 401;
int SC_PAYMENT_REQUIRED = 402; int SC_PAYMENT_REQUIRED = 402;
int SC_FORBIDDEN = 403; int SC_FORBIDDEN = 403;
int SC_NOT_FOUND = 404; int SC_NOT_FOUND = 404;
int SC_METHOD_NOT_ALLOWED = 405; int SC_METHOD_NOT_ALLOWED = 405;
int SC_NOT_ACCEPTABLE = 406; int SC_NOT_ACCEPTABLE = 406;
int SC_PROXY_AUTHENTICATION_REQUIRED = 407; int SC_PROXY_AUTHENTICATION_REQUIRED = 407;
int SC_REQUEST_TIMEOUT = 408; int SC_REQUEST_TIMEOUT = 408;
int SC_CONFLICT = 409; int SC_CONFLICT = 409;
int SC_GONE = 410; int SC_GONE = 410;
int SC_LENGTH_REQUIRED = 411; int SC_LENGTH_REQUIRED = 411;
int SC_PRECONDITION_FAILED = 412; int SC_PRECONDITION_FAILED = 412;
int SC_REQUEST_ENTITY_TOO_LARGE = 413; int SC_REQUEST_ENTITY_TOO_LARGE = 413;
int SC_REQUEST_URI_TOO_LONG = 414; int SC_REQUEST_URI_TOO_LONG = 414;
int SC_UNSUPPORTED_MEDIA_TYPE = 415; int SC_UNSUPPORTED_MEDIA_TYPE = 415;
int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416; int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
int SC_EXPECTATION_FAILED = 417; int SC_EXPECTATION_FAILED = 417;
int SC_INTERNAL_SERVER_ERROR = 500; int SC_INTERNAL_SERVER_ERROR = 500;
int SC_NOT_IMPLEMENTED = 501; int SC_NOT_IMPLEMENTED = 501;
int SC_BAD_GATEWAY = 502; int SC_BAD_GATEWAY = 502;
int SC_SERVICE_UNAVAILABLE = 503; int SC_SERVICE_UNAVAILABLE = 503;
int SC_GATEWAY_TIMEOUT = 504; int SC_GATEWAY_TIMEOUT = 504;
int SC_HTTP_VERSION_NOT_SUPPORTED = 505; int SC_HTTP_VERSION_NOT_SUPPORTED = 505;
} }

@ -34,7 +34,7 @@ import java.util.zip.GZIPOutputStream;
* *
* @author nacos * @author nacos
*/ */
public class IoUtils { public class IoUtil {
/** /**
* Try decompress by GZIP from stream. * Try decompress by GZIP from stream.
@ -173,7 +173,7 @@ public class IoUtils {
public static long copy(Reader input, Writer output) throws IOException { public static long copy(Reader input, Writer output) throws IOException {
char[] buffer = new char[1 << 12]; char[] buffer = new char[1 << 12];
long count = 0; long count = 0;
for (int n = 0; (n = input.read(buffer)) >= 0;) { for (int n = 0; (n = input.read(buffer)) >= 0; ) {
output.write(buffer, 0, n); output.write(buffer, 0, n);
count += n; count += n;
} }
@ -336,6 +336,6 @@ public class IoUtils {
} }
public static void closeQuietly(Closeable... closeable) { public static void closeQuietly(Closeable... closeable) {
Arrays.stream(closeable).forEach(IoUtils::closeQuietly); Arrays.stream(closeable).forEach(IoUtil::closeQuietly);
} }
} }

@ -78,8 +78,8 @@ public class JacksonHandler implements JsonFacade {
try { try {
MAPPER.readTree(text); MAPPER.readTree(text);
return true; return true;
} catch (JsonProcessingException jpe) { } catch (JsonProcessingException ignored) {
return false;
} }
return false;
} }
} }

@ -25,7 +25,7 @@ import java.util.function.BiFunction;
import java.util.function.Predicate; import java.util.function.Predicate;
/** /**
* Map utils. * Map util.
*/ */
public class MapUtil { public class MapUtil {
@ -137,13 +137,11 @@ public class MapUtil {
*/ */
public static <K, C, V, T> V computeIfAbsent(Map<K, V> target, K key, BiFunction<C, T, V> mappingFunction, C param1, public static <K, C, V, T> V computeIfAbsent(Map<K, V> target, K key, BiFunction<C, T, V> mappingFunction, C param1,
T param2) { T param2) {
Objects.requireNonNull(target, "target"); Objects.requireNonNull(target, "target");
Objects.requireNonNull(key, "key"); Objects.requireNonNull(key, "key");
Objects.requireNonNull(mappingFunction, "mappingFunction"); Objects.requireNonNull(mappingFunction, "mappingFunction");
Objects.requireNonNull(param1, "param1"); Objects.requireNonNull(param1, "param1");
Objects.requireNonNull(param2, "param2"); Objects.requireNonNull(param2, "param2");
V val = target.get(key); V val = target.get(key);
if (val == null) { if (val == null) {
V ret = mappingFunction.apply(param1, param2); V ret = mappingFunction.apply(param1, param2);
@ -156,11 +154,11 @@ public class MapUtil {
/** /**
* remove value, Thread safety depends on whether the Map is a thread-safe Map. * remove value, Thread safety depends on whether the Map is a thread-safe Map.
* *
* @param map map * @param map map
* @param key key * @param key key
* @param removeJudge judge this key can be remove * @param removeJudge judge this key can be remove
* @param <K> key type * @param <K> key type
* @param <V> value type * @param <V> value type
* @return value * @return value
*/ */
public static <K, V> V removeKey(Map<K, V> map, K key, Predicate<V> removeJudge) { public static <K, V> V removeKey(Map<K, V> map, K key, Predicate<V> removeJudge) {

@ -18,7 +18,7 @@
package cn.hippo4j.common.toolkit.http; package cn.hippo4j.common.toolkit.http;
import cn.hippo4j.common.constant.Constants; import cn.hippo4j.common.constant.Constants;
import cn.hippo4j.common.constant.HttpHeaderConsts; import cn.hippo4j.common.constant.HttpHeaderConstants;
import cn.hippo4j.common.constant.HttpMediaType; import cn.hippo4j.common.constant.HttpMediaType;
import cn.hippo4j.common.toolkit.MapUtil; import cn.hippo4j.common.toolkit.MapUtil;
import cn.hippo4j.common.toolkit.StringUtil; import cn.hippo4j.common.toolkit.StringUtil;
@ -45,9 +45,8 @@ public class Header {
private Header() { private Header() {
header = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); header = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
originalResponseHeader = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); originalResponseHeader = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
addParam(HttpHeaderConsts.CONTENT_TYPE, HttpMediaType.APPLICATION_JSON); addParam(HttpHeaderConstants.CONTENT_TYPE, HttpMediaType.APPLICATION_JSON);
addParam(HttpHeaderConsts.ACCEPT_CHARSET, DEFAULT_CHARSET); addParam(HttpHeaderConstants.ACCEPT_CHARSET, DEFAULT_CHARSET);
// addParam(HttpHeaderConsts.ACCEPT_ENCODING, DEFAULT_ENCODING);
} }
public static Header newInstance() { public static Header newInstance() {
@ -57,7 +56,7 @@ public class Header {
/** /**
* Add the key and value to the header. * Add the key and value to the header.
* *
* @param key the key * @param key the key
* @param value the value * @param value the value
* @return header * @return header
*/ */
@ -72,7 +71,7 @@ public class Header {
if (contentType == null) { if (contentType == null) {
contentType = HttpMediaType.APPLICATION_JSON; contentType = HttpMediaType.APPLICATION_JSON;
} }
return addParam(HttpHeaderConsts.CONTENT_TYPE, contentType); return addParam(HttpHeaderConstants.CONTENT_TYPE, contentType);
} }
public Header build() { public Header build() {
@ -144,7 +143,7 @@ public class Header {
* *
* <p>Currently only corresponds to the response header of JDK. * <p>Currently only corresponds to the response header of JDK.
* *
* @param key original response header key * @param key original response header key
* @param values original response header values * @param values original response header values
*/ */
public void addOriginalResponseHeader(String key, List<String> values) { public void addOriginalResponseHeader(String key, List<String> values) {
@ -166,9 +165,9 @@ public class Header {
} }
public String getCharset() { public String getCharset() {
String acceptCharset = getValue(HttpHeaderConsts.ACCEPT_CHARSET); String acceptCharset = getValue(HttpHeaderConstants.ACCEPT_CHARSET);
if (acceptCharset == null) { if (acceptCharset == null) {
String contentType = getValue(HttpHeaderConsts.CONTENT_TYPE); String contentType = getValue(HttpHeaderConstants.CONTENT_TYPE);
acceptCharset = StringUtil.isNotBlank(contentType) ? analysisCharset(contentType) : Constants.ENCODE; acceptCharset = StringUtil.isNotBlank(contentType) ? analysisCharset(contentType) : Constants.ENCODE;
} }
return acceptCharset; return acceptCharset;

@ -57,6 +57,7 @@ public interface HttpClientResponse extends Closeable {
/** /**
* Return the body As string. * Return the body As string.
*
* @return * @return
*/ */
String getBodyString(); String getBodyString();

@ -21,106 +21,224 @@ import cn.hippo4j.common.constant.Constants;
import cn.hippo4j.common.constant.HttpMediaType; import cn.hippo4j.common.constant.HttpMediaType;
import cn.hippo4j.common.constant.HttpMethod; import cn.hippo4j.common.constant.HttpMethod;
import cn.hippo4j.common.constant.HttpResponseCode; import cn.hippo4j.common.constant.HttpResponseCode;
import cn.hippo4j.common.toolkit.IoUtils; import cn.hippo4j.common.toolkit.CollectionUtil;
import cn.hippo4j.common.toolkit.IoUtil;
import cn.hippo4j.common.toolkit.JSONUtil; import cn.hippo4j.common.toolkit.JSONUtil;
import cn.hippo4j.common.toolkit.StringUtil; import cn.hippo4j.common.toolkit.StringUtil;
import cn.hippo4j.common.toolkit.logtracing.LogMessage; import cn.hippo4j.common.toolkit.logtracing.LogMessage;
import cn.hippo4j.common.web.exception.ServiceException; import cn.hippo4j.common.web.exception.ServiceException;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows; import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import java.io.OutputStream; import java.io.OutputStream;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.util.Map; import java.util.Map;
import java.util.Optional;
import static cn.hippo4j.common.constant.HttpHeaderConsts.CONTENT_LENGTH; import static cn.hippo4j.common.constant.HttpHeaderConstants.CONTENT_LENGTH;
/** /**
* Http request utilities. * Http request utilities.
*
* @author Rongzhen Yan * @author Rongzhen Yan
*/ */
@Slf4j @Slf4j
public class HttpUtils { @NoArgsConstructor(access = AccessLevel.PRIVATE)
public class HttpUtil {
private static final int CONNECT_TIMEOUT = 10000; /**
* Default connect timeout
*/
private static final int DEFAULT_CONNECT_TIMEOUT = 10000;
private static final int READ_TIMEOUT = 300000; /**
* Default read timeout
*/
private static final int DEFAULT_READ_TIMEOUT = 30000;
private HttpUtils() { /**
* Send a get network request.
*
* @param url target url
* @param headers headers
* @param params form data
* @param timeout request timeout
* @param clazz return the target data type
* @param <T> return the target data type
* @return
*/
public static <T> T get(String url, Map<String, String> headers, Map<String, String> params, long timeout, Class<T> clazz) {
return execute(buildUrl(url, params), HttpMethod.GET, null, headers, timeout, clazz);
} }
/**
* Send a get network request.
*
* @param url target url
* @param params form data
* @return
*/
public static String get(String url, Map<String, String> params) {
return execute(buildUrl(url, params), HttpMethod.GET, null, null);
}
/**
* Send a get network request.
*
* @param url target url
* @return
*/
public static String get(String url) {
return execute(url, HttpMethod.GET, null, null);
}
/**
* Send a get network request.
*
* @param url target url
* @param clazz return the target data type
* @param <T> return the target data type
* @return
*/
public static <T> T get(String url, Class<T> clazz) {
return JSONUtil.parseObject(get(url), clazz);
}
/**
* Send a post network request.
*
* @param url target url
* @param body request body
* @param clazz return the target data type
* @param <T> return the target data type
* @return
*/
public static <T> T post(String url, Object body, Class<T> clazz) { public static <T> T post(String url, Object body, Class<T> clazz) {
String result = post(url, body); String result = post(url, body);
return JSONUtil.parseObject(result, clazz); return JSONUtil.parseObject(result, clazz);
} }
public static <T> T post(String url, Object body, long timeoutMillis, Class<T> clazz) { /**
String result = post(url, body, timeoutMillis); * Send a post network request.
*
* @param url target url
* @param body request body
* @param timeout request timeout
* @param clazz return the target data type
* @param <T> return the target data type
* @return
*/
public static <T> T post(String url, Object body, long timeout, Class<T> clazz) {
String result = post(url, body, timeout);
return JSONUtil.parseObject(result, clazz); return JSONUtil.parseObject(result, clazz);
} }
public static <T> T post(String url, Map<String, String> headers, Map<String, String> params, long timeoutMillis, Class<T> clazz) { /**
String result = execute(buildUrl(url, params), HttpMethod.POST, null, headers, timeoutMillis).getBodyString(); * Send a post network request.
return JSONUtil.parseObject(result, clazz); *
* @param url target url
* @param headers headers
* @param params form data
* @param timeout request timeout
* @param clazz return the target data type
* @param <T> return the target data type
* @return
*/
public static <T> T post(String url, Map<String, String> headers, Map<String, String> params, long timeout, Class<T> clazz) {
return execute(buildUrl(url, params), HttpMethod.POST, null, headers, timeout, clazz);
} }
public static <T> T post(String url, Map<String, String> headers, Object body, long timeoutMillis, Class<T> clazz) { /**
String result = execute(url, HttpMethod.POST, body, headers, timeoutMillis).getBodyString(); * Send a post network request.
return JSONUtil.parseObject(result, clazz); *
* @param url target url
* @param headers headers
* @param body request body
* @param timeout request timeout
* @param clazz return the target data type
* @param <T> return the target data type
* @return
*/
public static <T> T post(String url, Map<String, String> headers, Object body, long timeout, Class<T> clazz) {
return execute(url, HttpMethod.POST, body, headers, timeout, clazz);
} }
/**
* Send a post network request.
*
* @param url target url
* @param body request body
* @return
*/
public static String post(String url, Object body) { public static String post(String url, Object body) {
return execute(url, HttpMethod.POST, body, null).getBodyString(); return execute(url, HttpMethod.POST, body, null);
} }
public static String post(String url, Object body, long timeoutMillis) { /**
return execute(url, HttpMethod.POST, body, null, timeoutMillis).getBodyString(); * Send a post network request.
*
* @param url target url
* @param body request body
* @param timeout request timeout
* @return
*/
public static String post(String url, Object body, long timeout) {
return execute(url, HttpMethod.POST, body, null, timeout, String.class);
} }
/**
* Send a post network request.
*
* @param url target url
* @param json json data
* @return
*/
public static String postJson(String url, String json) { public static String postJson(String url, String json) {
return executeJson(url, HttpMethod.POST, json, null).getBodyString(); return executeJson(url, HttpMethod.POST, json, null);
} }
/**
* Send a put network request.
*
* @param url target url
* @param body request body
* @return
*/
public static String put(String url, Object body) { public static String put(String url, Object body) {
return execute(url, HttpMethod.PUT, body, null).getBodyString(); return execute(url, HttpMethod.PUT, body, null);
} }
/**
* Send a put network request.
*
* @param url target url
* @param body request body
* @param headers headers
* @return
*/
public static String put(String url, Object body, Map<String, String> headers) { public static String put(String url, Object body, Map<String, String> headers) {
return execute(url, HttpMethod.PUT, body, headers).getBodyString(); return execute(url, HttpMethod.PUT, body, headers);
}
public static <T> T get(String url, Map<String, String> headers, Map<String, String> params, long readTimeoutMillis, Class<T> clazz) {
String result = execute(buildUrl(url, params), HttpMethod.GET, null, headers, readTimeoutMillis).getBodyString();
return JSONUtil.parseObject(result, clazz);
}
public static String get(String url, Map<String, String> params) {
return execute(buildUrl(url, params), HttpMethod.GET, null, null).getBodyString();
}
public static String get(String url) {
return execute(url, HttpMethod.GET, null, null).getBodyString();
}
public static <T> T get(String url, Class<T> clazz) {
return JSONUtil.parseObject(get(url), clazz);
} }
/** /**
* Constructs a complete Url from the query string. * Constructs a complete Url from the query string.
* @param url *
* @param queryString * @param url target url
* @param queryParams query params
* @return * @return
*/ */
@SneakyThrows @SneakyThrows
public static String buildUrl(String url, Map<String, String> queryString) { public static String buildUrl(String url, Map<String, String> queryParams) {
if (null == queryString) { if (CollectionUtil.isEmpty(queryParams)) {
return url; return url;
} }
StringBuilder builder = new StringBuilder(url);
boolean isFirst = true; boolean isFirst = true;
for (Map.Entry<String, String> entry : queryString.entrySet()) { StringBuilder builder = new StringBuilder(url);
for (Map.Entry<String, String> entry : queryParams.entrySet()) {
String key = entry.getKey(); String key = entry.getKey();
if (key != null && entry.getValue() != null) { if (key != null && entry.getValue() != null) {
if (isFirst) { if (isFirst) {
@ -129,7 +247,7 @@ public class HttpUtils {
} else { } else {
builder.append("&"); builder.append("&");
} }
String value = URLEncoder.encode(queryString.get(key), Constants.ENCODE) String value = URLEncoder.encode(queryParams.get(key), Constants.ENCODE)
.replaceAll("\\+", "%20"); .replaceAll("\\+", "%20");
builder.append(key) builder.append(key)
.append("=") .append("=")
@ -139,17 +257,49 @@ public class HttpUtils {
return builder.toString(); return builder.toString();
} }
public static HttpClientResponse execute(String url, String method, Object param, Map<String, String> headers) { private static String executeJson(String url, String method, String json, Map<String, String> headers) {
if (!JSONUtil.isJson(json)) {
log.error(LogMessage.getInstance().setMsg("Http Call error.")
.kv("url", url)
.kv("method", method)
.kv("json", json)
.kv2String("headers", JSONUtil.toJSONString(headers)));
throw new ServiceException("Invalid http json body, please check it again.");
}
return execute(url, method, json, headers);
}
private static String execute(String url, String method, Object param, Map<String, String> headers) {
HttpURLConnection connection = createConnection(url, method); HttpURLConnection connection = createConnection(url, method);
return doExecute(connection, param, headers); HttpClientResponse response = null;
try {
response = doExecute(connection, param, headers);
return response.getBodyString();
} finally {
Optional.ofNullable(response).ifPresent(each -> each.close());
}
}
private static <T> T execute(String url, String method, Object body, Map<String, String> headers, long timeout, Class<T> clazz) {
HttpURLConnection connection = createConnection(url, method, timeout);
HttpClientResponse response = null;
try {
response = doExecute(connection, body, headers);
if (clazz == String.class) {
return (T) response.getBodyString();
}
return JSONUtil.parseObject(response.getBodyString(), clazz);
} finally {
Optional.ofNullable(response).ifPresent(each -> each.close());
}
} }
@SneakyThrows @SneakyThrows
public static HttpClientResponse doExecute(HttpURLConnection connection, Object body, Map<String, String> headers) { private static HttpClientResponse doExecute(HttpURLConnection connection, Object body, Map<String, String> headers) {
try { try {
if (headers != null) { if (headers != null && headers.size() > 0) {
for (String key : headers.keySet()) { for (Map.Entry<String, String> entry : headers.entrySet()) {
connection.setRequestProperty(key, headers.get(key)); connection.setRequestProperty(entry.getKey(), entry.getValue());
} }
} }
String bodyString; String bodyString;
@ -165,7 +315,7 @@ public class HttpUtils {
OutputStream outputStream = connection.getOutputStream(); OutputStream outputStream = connection.getOutputStream();
outputStream.write(b, 0, b.length); outputStream.write(b, 0, b.length);
outputStream.flush(); outputStream.flush();
IoUtils.closeQuietly(outputStream); IoUtil.closeQuietly(outputStream);
} }
connection.connect(); connection.connect();
JdkHttpClientResponse response = new JdkHttpClientResponse(connection); JdkHttpClientResponse response = new JdkHttpClientResponse(connection);
@ -174,31 +324,14 @@ public class HttpUtils {
throw new ServiceException(msg); throw new ServiceException(msg);
} }
return response; return response;
} catch (Throwable e) { } catch (Throwable ex) {
log.error(LogMessage.getInstance().setMsg("Http Call error.") log.error(LogMessage.getInstance().setMsg("Http call error. ")
.kv("url", connection.getURL()) .kv("url", connection.getURL())
.kv("method", connection.getRequestMethod()) .kv("method", connection.getRequestMethod())
.kv("body", JSONUtil.toJSONString(body)) .kv("body", JSONUtil.toJSONString(body))
.kv2String("headers", JSONUtil.toJSONString(headers)), e); .kv2String("headers", JSONUtil.toJSONString(headers)), ex);
throw e; throw ex;
}
}
public static HttpClientResponse execute(String url, String method, Object body, Map<String, String> headers, long timeout) {
HttpURLConnection connection = createConnection(url, method, timeout);
return doExecute(connection, body, headers);
}
public static HttpClientResponse executeJson(String url, String method, String json, Map<String, String> headers) {
if (!JSONUtil.isJson(json)) {
log.error(LogMessage.getInstance().setMsg("Http Call error.")
.kv("url", url)
.kv("method", method)
.kv("json", json)
.kv2String("headers", JSONUtil.toJSONString(headers)));
throw new ServiceException("invalid http json body, please check it again.");
} }
return execute(url, method, json, headers);
} }
@SneakyThrows @SneakyThrows
@ -206,8 +339,8 @@ public class HttpUtils {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setDoInput(true); connection.setDoInput(true);
connection.setDoOutput(true); connection.setDoOutput(true);
connection.setConnectTimeout(CONNECT_TIMEOUT); connection.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT);
connection.setReadTimeout(READ_TIMEOUT); connection.setReadTimeout(DEFAULT_READ_TIMEOUT);
connection.setRequestMethod(method); connection.setRequestMethod(method);
connection.setRequestProperty(Constants.CONTENT_TYPE, HttpMediaType.APPLICATION_JSON); connection.setRequestProperty(Constants.CONTENT_TYPE, HttpMediaType.APPLICATION_JSON);
return connection; return connection;
@ -216,7 +349,6 @@ public class HttpUtils {
@SneakyThrows @SneakyThrows
private static HttpURLConnection createConnection(String url, String method, long timeout) { private static HttpURLConnection createConnection(String url, String method, long timeout) {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setDoInput(true); connection.setDoInput(true);
connection.setDoOutput(true); connection.setDoOutput(true);
connection.setConnectTimeout(Integer.parseInt(String.valueOf(timeout))); connection.setConnectTimeout(Integer.parseInt(String.valueOf(timeout)));

@ -18,8 +18,8 @@
package cn.hippo4j.common.toolkit.http; package cn.hippo4j.common.toolkit.http;
import cn.hippo4j.common.constant.Constants; import cn.hippo4j.common.constant.Constants;
import cn.hippo4j.common.constant.HttpHeaderConsts; import cn.hippo4j.common.constant.HttpHeaderConstants;
import cn.hippo4j.common.toolkit.IoUtils; import cn.hippo4j.common.toolkit.IoUtil;
import lombok.SneakyThrows; import lombok.SneakyThrows;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
@ -64,10 +64,10 @@ public class JdkHttpClientResponse implements HttpClientResponse {
Header headers = getHeaders(); Header headers = getHeaders();
InputStream errorStream = this.conn.getErrorStream(); InputStream errorStream = this.conn.getErrorStream();
this.responseStream = (errorStream != null ? errorStream : this.conn.getInputStream()); this.responseStream = (errorStream != null ? errorStream : this.conn.getInputStream());
String contentEncoding = headers.getValue(HttpHeaderConsts.CONTENT_ENCODING); String contentEncoding = headers.getValue(HttpHeaderConstants.CONTENT_ENCODING);
// Used to process http content_encoding, when content_encoding is GZIP, use GZIPInputStream // Used to process http content_encoding, when content_encoding is GZIP, use GZIPInputStream
if (CONTENT_ENCODING.equals(contentEncoding)) { if (CONTENT_ENCODING.equals(contentEncoding)) {
byte[] bytes = IoUtils.tryDecompress(this.responseStream); byte[] bytes = IoUtil.tryDecompress(this.responseStream);
return new ByteArrayInputStream(bytes); return new ByteArrayInputStream(bytes);
} }
return this.responseStream; return this.responseStream;
@ -87,11 +87,11 @@ public class JdkHttpClientResponse implements HttpClientResponse {
@Override @Override
public String getBodyString() { public String getBodyString() {
return IoUtils.toString(this.getBody(), Constants.ENCODE); return IoUtil.toString(this.getBody(), Constants.ENCODE);
} }
@Override @Override
public void close() { public void close() {
IoUtils.closeQuietly(this.responseStream); IoUtil.closeQuietly(this.responseStream);
} }
} }

@ -17,6 +17,9 @@
package cn.hippo4j.common.toolkit.logtracing; package cn.hippo4j.common.toolkit.logtracing;
import cn.hippo4j.common.toolkit.StringUtil;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.slf4j.helpers.FormattingTuple; import org.slf4j.helpers.FormattingTuple;
import org.slf4j.helpers.MessageFormatter; import org.slf4j.helpers.MessageFormatter;
@ -24,16 +27,16 @@ import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
/** /**
* KV * Log message.
*
* @author Rongzhen Yan * @author Rongzhen Yan
*/ */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class LogMessage { public class LogMessage {
private Map<String, Object> kvs = new ConcurrentHashMap<>(); private Map<String, Object> kvs = new ConcurrentHashMap<>();
private String msg = "";
private LogMessage() { private String msg = "";
}
public static LogMessage getInstance() { public static LogMessage getInstance() {
return new LogMessage(); return new LogMessage();
@ -75,16 +78,23 @@ public class LogMessage {
@Override @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
if (StringUtil.isNotEmpty(msg)) {
if (msg != null && !msg.isEmpty()) { sb.append(msg);
sb.append("||_msg=").append(msg);
} }
int tempCount = 0;
for (Map.Entry<String, Object> kv : kvs.entrySet()) { for (Map.Entry<String, Object> kv : kvs.entrySet()) {
sb.append("||" + kv.getKey() + "=").append(kv.getValue()); tempCount++;
Object value = kv.getValue();
if (value != null) {
if (value instanceof String && StringUtil.isEmpty((String) value)) {
continue;
}
sb.append(kv.getKey() + "=").append(kv.getValue());
if (tempCount != kvs.size()) {
sb.append("||");
}
}
} }
return sb.toString(); return sb.toString();
} }
} }

@ -41,7 +41,7 @@ public class HttpUtilsTest {
@Test @Test
public void get() { public void get() {
String s = HttpUtils.get(getUrl); String s = HttpUtil.get(getUrl);
Assert.assertNotNull(s); Assert.assertNotNull(s);
} }
@ -52,7 +52,7 @@ public class HttpUtilsTest {
loginInfo.setPassword("hippo4j"); loginInfo.setPassword("hippo4j");
loginInfo.setUsername("hippo4j"); loginInfo.setUsername("hippo4j");
loginInfo.setRememberMe(1); loginInfo.setRememberMe(1);
String s = HttpUtils.post(loginUrl, loginInfo); String s = HttpUtil.post(loginUrl, loginInfo);
Result result = JSONUtil.parseObject(s, Result.class); Result result = JSONUtil.parseObject(s, Result.class);
Assert.assertNotNull(result); Assert.assertNotNull(result);
String data = result.getData().getData(); String data = result.getData().getData();
@ -66,7 +66,7 @@ public class HttpUtilsTest {
loginInfo.setPassword("hippo4j"); loginInfo.setPassword("hippo4j");
loginInfo.setUsername("hippo4j"); loginInfo.setUsername("hippo4j");
loginInfo.setRememberMe(1); loginInfo.setRememberMe(1);
Result result = HttpUtils.post(loginUrl, loginInfo, Result.class); Result result = HttpUtil.post(loginUrl, loginInfo, Result.class);
Assert.assertNotNull(result); Assert.assertNotNull(result);
String data = result.getData().getData(); String data = result.getData().getData();
Assert.assertNotNull(data); Assert.assertNotNull(data);
@ -79,7 +79,7 @@ public class HttpUtilsTest {
loginInfo.setPassword("hippo4j"); loginInfo.setPassword("hippo4j");
loginInfo.setUsername("hippo4j"); loginInfo.setUsername("hippo4j");
loginInfo.setRememberMe(1); loginInfo.setRememberMe(1);
Assert.assertThrows(SocketTimeoutException.class, () -> HttpUtils.post(loginUrl, loginInfo, 1, Result.class)); Assert.assertThrows(SocketTimeoutException.class, () -> HttpUtil.post(loginUrl, loginInfo, 1, Result.class));
} }
@Test @Test
@ -87,7 +87,7 @@ public class HttpUtilsTest {
Map<String, String> map = new HashMap<>(); Map<String, String> map = new HashMap<>();
map.put("password", "hippo4j"); map.put("password", "hippo4j");
map.put("username", "hippo4j"); map.put("username", "hippo4j");
String s = HttpUtils.buildUrl(getUrl, map); String s = HttpUtil.buildUrl(getUrl, map);
Assert.assertEquals(getUrl + "?password=hippo4j&username=hippo4j", s); Assert.assertEquals(getUrl + "?password=hippo4j&username=hippo4j", s);
} }
@ -96,7 +96,9 @@ public class HttpUtilsTest {
private static class LoginInfo { private static class LoginInfo {
private String username; private String username;
private String password; private String password;
private Integer rememberMe; private Integer rememberMe;
} }
@ -105,6 +107,7 @@ public class HttpUtilsTest {
private static class Result { private static class Result {
private String code; private String code;
private ResultData data; private ResultData data;
} }
@ -113,6 +116,7 @@ public class HttpUtilsTest {
private static class ResultData { private static class ResultData {
private String data; private String data;
private String[] roles; private String[] roles;
} }
} }

@ -25,7 +25,7 @@ import cn.hippo4j.common.design.observer.ObserverMessage;
import cn.hippo4j.common.toolkit.CollectionUtil; import cn.hippo4j.common.toolkit.CollectionUtil;
import cn.hippo4j.common.toolkit.JSONUtil; import cn.hippo4j.common.toolkit.JSONUtil;
import cn.hippo4j.common.toolkit.StringUtil; import cn.hippo4j.common.toolkit.StringUtil;
import cn.hippo4j.common.toolkit.http.HttpUtils; import cn.hippo4j.common.toolkit.http.HttpUtil;
import cn.hippo4j.common.web.base.Result; import cn.hippo4j.common.web.base.Result;
import cn.hippo4j.config.model.biz.adapter.ThreadPoolAdapterReqDTO; import cn.hippo4j.config.model.biz.adapter.ThreadPoolAdapterReqDTO;
import cn.hippo4j.config.model.biz.adapter.ThreadPoolAdapterRespDTO; import cn.hippo4j.config.model.biz.adapter.ThreadPoolAdapterRespDTO;
@ -101,7 +101,7 @@ public class ThreadPoolAdapterService {
param.put("mark", requestParameter.getMark()); param.put("mark", requestParameter.getMark());
param.put("threadPoolKey", requestParameter.getThreadPoolKey()); param.put("threadPoolKey", requestParameter.getThreadPoolKey());
try { try {
String resultStr = HttpUtils.get(url, param); String resultStr = HttpUtil.get(url, param);
if (StringUtil.isNotBlank(resultStr)) { if (StringUtil.isNotBlank(resultStr)) {
Result<ThreadPoolAdapterRespDTO> restResult = JSONUtil.parseObject(resultStr, new TypeReference<Result<ThreadPoolAdapterRespDTO>>() { Result<ThreadPoolAdapterRespDTO> restResult = JSONUtil.parseObject(resultStr, new TypeReference<Result<ThreadPoolAdapterRespDTO>>() {
}); });

@ -19,7 +19,7 @@ package cn.hippo4j.config.service.biz.impl;
import cn.hippo4j.common.constant.ConfigModifyTypeConstants; import cn.hippo4j.common.constant.ConfigModifyTypeConstants;
import cn.hippo4j.common.toolkit.StringUtil; import cn.hippo4j.common.toolkit.StringUtil;
import cn.hippo4j.common.toolkit.http.HttpUtils; import cn.hippo4j.common.toolkit.http.HttpUtil;
import cn.hippo4j.config.model.biz.threadpool.ConfigModifyVerifyReqDTO; import cn.hippo4j.config.model.biz.threadpool.ConfigModifyVerifyReqDTO;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -40,7 +40,7 @@ public class AdapterThreadPoolConfigModificationVerifyServiceImpl extends Abstra
protected void updateThreadPoolParameter(ConfigModifyVerifyReqDTO reqDTO) { protected void updateThreadPoolParameter(ConfigModifyVerifyReqDTO reqDTO) {
for (String each : getClientAddress(reqDTO)) { for (String each : getClientAddress(reqDTO)) {
String urlString = StringUtil.newBuilder("http://", each, "/adapter/thread-pool/update"); String urlString = StringUtil.newBuilder("http://", each, "/adapter/thread-pool/update");
HttpUtils.post(urlString, reqDTO); HttpUtil.post(urlString, reqDTO);
} }
} }
} }

@ -19,7 +19,7 @@ package cn.hippo4j.config.service.biz.impl;
import cn.hippo4j.common.constant.ConfigModifyTypeConstants; import cn.hippo4j.common.constant.ConfigModifyTypeConstants;
import cn.hippo4j.common.toolkit.StringUtil; import cn.hippo4j.common.toolkit.StringUtil;
import cn.hippo4j.common.toolkit.http.HttpUtils; import cn.hippo4j.common.toolkit.http.HttpUtil;
import cn.hippo4j.config.model.biz.threadpool.ConfigModifyVerifyReqDTO; import cn.hippo4j.config.model.biz.threadpool.ConfigModifyVerifyReqDTO;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -40,7 +40,7 @@ public class WebThreadPoolConfigModificationVerifyServiceImpl extends AbstractCo
protected void updateThreadPoolParameter(ConfigModifyVerifyReqDTO reqDTO) { protected void updateThreadPoolParameter(ConfigModifyVerifyReqDTO reqDTO) {
for (String each : getClientAddress(reqDTO)) { for (String each : getClientAddress(reqDTO)) {
String urlString = StringUtil.newBuilder("http://", each, "/web/update/pool"); String urlString = StringUtil.newBuilder("http://", each, "/web/update/pool");
HttpUtils.post(urlString, reqDTO); HttpUtil.post(urlString, reqDTO);
} }
} }
} }

@ -19,7 +19,7 @@ package cn.hippo4j.console.controller;
import cn.hippo4j.common.constant.ConfigModifyTypeConstants; import cn.hippo4j.common.constant.ConfigModifyTypeConstants;
import cn.hippo4j.common.toolkit.*; import cn.hippo4j.common.toolkit.*;
import cn.hippo4j.common.toolkit.http.HttpUtils; import cn.hippo4j.common.toolkit.http.HttpUtil;
import cn.hippo4j.common.web.base.Result; import cn.hippo4j.common.web.base.Result;
import cn.hippo4j.common.web.base.Results; import cn.hippo4j.common.web.base.Results;
import cn.hippo4j.config.model.biz.adapter.ThreadPoolAdapterReqDTO; import cn.hippo4j.config.model.biz.adapter.ThreadPoolAdapterReqDTO;
@ -66,7 +66,7 @@ public class ThreadPoolAdapterController {
if (UserContext.getUserRole().equals("ROLE_ADMIN")) { if (UserContext.getUserRole().equals("ROLE_ADMIN")) {
for (String each : requestParameter.getClientAddressList()) { for (String each : requestParameter.getClientAddressList()) {
String urlString = StringUtil.newBuilder("http://", each, "/adapter/thread-pool/update"); String urlString = StringUtil.newBuilder("http://", each, "/adapter/thread-pool/update");
HttpUtils.post(urlString, requestParameter); HttpUtil.post(urlString, requestParameter);
} }
} else { } else {
ConfigModifySaveReqDTO modifySaveReqDTO = BeanUtil.convert(requestParameter, ConfigModifySaveReqDTO.class); ConfigModifySaveReqDTO modifySaveReqDTO = BeanUtil.convert(requestParameter, ConfigModifySaveReqDTO.class);

@ -21,7 +21,7 @@ import cn.hippo4j.common.constant.ConfigModifyTypeConstants;
import cn.hippo4j.common.constant.Constants; import cn.hippo4j.common.constant.Constants;
import cn.hippo4j.common.model.InstanceInfo; import cn.hippo4j.common.model.InstanceInfo;
import cn.hippo4j.common.toolkit.*; import cn.hippo4j.common.toolkit.*;
import cn.hippo4j.common.toolkit.http.HttpUtils; import cn.hippo4j.common.toolkit.http.HttpUtil;
import cn.hippo4j.common.web.base.Result; import cn.hippo4j.common.web.base.Result;
import cn.hippo4j.common.web.base.Results; import cn.hippo4j.common.web.base.Results;
import cn.hippo4j.common.web.exception.ErrorCodeEnum; import cn.hippo4j.common.web.exception.ErrorCodeEnum;
@ -109,14 +109,14 @@ public class ThreadPoolController {
public Result runState(@PathVariable("tpId") String tpId, public Result runState(@PathVariable("tpId") String tpId,
@RequestParam(value = "clientAddress") String clientAddress) { @RequestParam(value = "clientAddress") String clientAddress) {
String urlString = StringUtil.newBuilder(HTTP, clientAddress, "/run/state/", tpId); String urlString = StringUtil.newBuilder(HTTP, clientAddress, "/run/state/", tpId);
return HttpUtils.get(urlString, Result.class); return HttpUtil.get(urlString, Result.class);
} }
@GetMapping("/run/thread/state/{tpId}") @GetMapping("/run/thread/state/{tpId}")
public Result runThreadState(@PathVariable("tpId") String tpId, public Result runThreadState(@PathVariable("tpId") String tpId,
@RequestParam(value = "clientAddress") String clientAddress) { @RequestParam(value = "clientAddress") String clientAddress) {
String urlString = StringUtil.newBuilder(HTTP, clientAddress, "/run/thread/state/", tpId); String urlString = StringUtil.newBuilder(HTTP, clientAddress, "/run/thread/state/", tpId);
return HttpUtils.get(urlString, Result.class); return HttpUtil.get(urlString, Result.class);
} }
@GetMapping("/list/client/instance/{itemId}") @GetMapping("/list/client/instance/{itemId}")
@ -152,13 +152,13 @@ public class ThreadPoolController {
@GetMapping("/web/base/info") @GetMapping("/web/base/info")
public Result getPoolBaseState(@RequestParam(value = "clientAddress") String clientAddress) { public Result getPoolBaseState(@RequestParam(value = "clientAddress") String clientAddress) {
String urlString = StringUtil.newBuilder(HTTP, clientAddress, "/web/base/info"); String urlString = StringUtil.newBuilder(HTTP, clientAddress, "/web/base/info");
return HttpUtils.get(urlString, Result.class); return HttpUtil.get(urlString, Result.class);
} }
@GetMapping("/web/run/state") @GetMapping("/web/run/state")
public Result getPoolRunState(@RequestParam(value = "clientAddress") String clientAddress) { public Result getPoolRunState(@RequestParam(value = "clientAddress") String clientAddress) {
String urlString = StringUtil.newBuilder(HTTP, clientAddress, "/web/run/state"); String urlString = StringUtil.newBuilder(HTTP, clientAddress, "/web/run/state");
return HttpUtils.get(urlString, Result.class); return HttpUtil.get(urlString, Result.class);
} }
@PostMapping("/web/update/pool") @PostMapping("/web/update/pool")
@ -166,7 +166,7 @@ public class ThreadPoolController {
if (UserContext.getUserRole().equals("ROLE_ADMIN")) { if (UserContext.getUserRole().equals("ROLE_ADMIN")) {
for (String each : requestParam.getClientAddressList()) { for (String each : requestParam.getClientAddressList()) {
String urlString = StringUtil.newBuilder(HTTP, each, "/web/update/pool"); String urlString = StringUtil.newBuilder(HTTP, each, "/web/update/pool");
HttpUtils.post(urlString, requestParam); HttpUtil.post(urlString, requestParam);
} }
} else { } else {
ConfigModifySaveReqDTO modifySaveReqDTO = BeanUtil.convert(requestParam, ConfigModifySaveReqDTO.class); ConfigModifySaveReqDTO modifySaveReqDTO = BeanUtil.convert(requestParam, ConfigModifySaveReqDTO.class);

@ -18,7 +18,7 @@
package cn.hippo4j.message.platform; package cn.hippo4j.message.platform;
import cn.hippo4j.common.toolkit.Singleton; import cn.hippo4j.common.toolkit.Singleton;
import cn.hippo4j.common.toolkit.http.HttpUtils; import cn.hippo4j.common.toolkit.http.HttpUtil;
import cn.hippo4j.message.dto.NotifyConfigDTO; import cn.hippo4j.message.dto.NotifyConfigDTO;
import cn.hippo4j.message.enums.NotifyPlatformEnum; import cn.hippo4j.message.enums.NotifyPlatformEnum;
import cn.hippo4j.message.enums.NotifyTypeEnum; import cn.hippo4j.message.enums.NotifyTypeEnum;
@ -75,7 +75,6 @@ public class LarkSendMessageHandler implements SendMessageHandler<AlarmNotifyReq
} else { } else {
larkAlarmTxt = StringUtil.replace(larkAlarmTxt, larkAlarmTimoutReplaceJson, ""); larkAlarmTxt = StringUtil.replace(larkAlarmTxt, larkAlarmTimoutReplaceJson, "");
} }
String text = String.format(larkAlarmTxt, String text = String.format(larkAlarmTxt,
// 环境 // 环境
alarmNotifyRequest.getActive(), alarmNotifyRequest.getActive(),
@ -172,7 +171,7 @@ public class LarkSendMessageHandler implements SendMessageHandler<AlarmNotifyReq
private void execute(String secretKey, String text) { private void execute(String secretKey, String text) {
String serverUrl = LARK_BOT_URL + secretKey; String serverUrl = LARK_BOT_URL + secretKey;
try { try {
HttpUtils.postJson(serverUrl, text); HttpUtil.postJson(serverUrl, text);
} catch (Exception ex) { } catch (Exception ex) {
log.error("Lark failed to send message", ex); log.error("Lark failed to send message", ex);
} }

@ -19,7 +19,7 @@ package cn.hippo4j.message.platform;
import cn.hippo4j.common.toolkit.FileUtil; import cn.hippo4j.common.toolkit.FileUtil;
import cn.hippo4j.common.toolkit.Singleton; import cn.hippo4j.common.toolkit.Singleton;
import cn.hippo4j.common.toolkit.http.HttpUtils; import cn.hippo4j.common.toolkit.http.HttpUtil;
import cn.hippo4j.message.enums.NotifyPlatformEnum; import cn.hippo4j.message.enums.NotifyPlatformEnum;
import cn.hippo4j.message.platform.base.AbstractRobotSendMessageHandler; import cn.hippo4j.message.platform.base.AbstractRobotSendMessageHandler;
import cn.hippo4j.message.platform.base.RobotMessageActualContent; import cn.hippo4j.message.platform.base.RobotMessageActualContent;
@ -64,8 +64,7 @@ public class WeChatSendMessageHandler extends AbstractRobotSendMessageHandler {
Markdown markdown = new Markdown(); Markdown markdown = new Markdown();
markdown.setContent(robotMessageExecuteDTO.getText()); markdown.setContent(robotMessageExecuteDTO.getText());
weChatReq.setMarkdown(markdown); weChatReq.setMarkdown(markdown);
HttpUtil.post(serverUrl, weChatReq);
HttpUtils.post(serverUrl, weChatReq);
} catch (Exception ex) { } catch (Exception ex) {
log.error("WeChat failed to send message", ex); log.error("WeChat failed to send message", ex);
} }

@ -158,7 +158,7 @@ public class ClientWorker {
headers.put(LONG_PULLING_TIMEOUT, "" + timeout); headers.put(LONG_PULLING_TIMEOUT, "" + timeout);
// Confirm the identity of the client, and can be modified separately when modifying the thread pool configuration. // Confirm the identity of the client, and can be modified separately when modifying the thread pool configuration.
headers.put(LONG_PULLING_CLIENT_IDENTIFICATION, identify); headers.put(LONG_PULLING_CLIENT_IDENTIFICATION, identify);
// told server do not hang me up if new initializing cacheData added in // Told server do not hang me up if new initializing cacheData added in.
if (isInitializingCacheList) { if (isInitializingCacheList) {
headers.put(LONG_PULLING_TIMEOUT_NO_HANGUP, "true"); headers.put(LONG_PULLING_TIMEOUT_NO_HANGUP, "true");
} }

@ -20,7 +20,7 @@ package cn.hippo4j.springboot.starter.remote;
import cn.hippo4j.common.config.ApplicationContextHolder; import cn.hippo4j.common.config.ApplicationContextHolder;
import cn.hippo4j.common.constant.Constants; import cn.hippo4j.common.constant.Constants;
import cn.hippo4j.common.toolkit.StringUtil; import cn.hippo4j.common.toolkit.StringUtil;
import cn.hippo4j.common.toolkit.http.HttpUtils; import cn.hippo4j.common.toolkit.http.HttpUtil;
import cn.hippo4j.common.web.base.Result; import cn.hippo4j.common.web.base.Result;
import cn.hippo4j.common.design.builder.ThreadFactoryBuilder; import cn.hippo4j.common.design.builder.ThreadFactoryBuilder;
import cn.hippo4j.springboot.starter.config.BootstrapProperties; import cn.hippo4j.springboot.starter.config.BootstrapProperties;
@ -82,35 +82,35 @@ public class ServerHttpAgent implements HttpAgent {
@Override @Override
public Result httpGetSimple(String path) { public Result httpGetSimple(String path) {
path = injectSecurityInfoByPath(path); path = injectSecurityInfoByPath(path);
return HttpUtils.get(buildUrl(path), Result.class); return HttpUtil.get(buildUrl(path), Result.class);
} }
@Override @Override
public Result httpPost(String path, Object body) { public Result httpPost(String path, Object body) {
isHealthStatus(); isHealthStatus();
path = injectSecurityInfoByPath(path); path = injectSecurityInfoByPath(path);
return HttpUtils.post(buildUrl(path), body, Result.class); return HttpUtil.post(buildUrl(path), body, Result.class);
} }
@Override @Override
public Result httpPostByDiscovery(String path, Object body) { public Result httpPostByDiscovery(String path, Object body) {
isHealthStatus(); isHealthStatus();
path = injectSecurityInfoByPath(path); path = injectSecurityInfoByPath(path);
return HttpUtils.post(buildUrl(path), body, Result.class); return HttpUtil.post(buildUrl(path), body, Result.class);
} }
@Override @Override
public Result httpGetByConfig(String path, Map<String, String> headers, Map<String, String> paramValues, long readTimeoutMs) { public Result httpGetByConfig(String path, Map<String, String> headers, Map<String, String> paramValues, long readTimeoutMs) {
isHealthStatus(); isHealthStatus();
injectSecurityInfo(paramValues); injectSecurityInfo(paramValues);
return HttpUtils.get(buildUrl(path), headers, paramValues, readTimeoutMs, Result.class); return HttpUtil.get(buildUrl(path), headers, paramValues, readTimeoutMs, Result.class);
} }
@Override @Override
public Result httpPostByConfig(String path, Map<String, String> headers, Map<String, String> paramValues, long readTimeoutMs) { public Result httpPostByConfig(String path, Map<String, String> headers, Map<String, String> paramValues, long readTimeoutMs) {
isHealthStatus(); isHealthStatus();
injectSecurityInfo(paramValues); injectSecurityInfo(paramValues);
return HttpUtils.post(buildUrl(path), headers, paramValues, readTimeoutMs, Result.class); return HttpUtil.post(buildUrl(path), headers, paramValues, readTimeoutMs, Result.class);
} }
@Override @Override
@ -138,7 +138,7 @@ public class ServerHttpAgent implements HttpAgent {
@Deprecated @Deprecated
private String injectSecurityInfoByPath(String path) { private String injectSecurityInfoByPath(String path) {
String resultPath = HttpUtils.buildUrl(path, injectSecurityInfo(new HashMap<>())); String resultPath = HttpUtil.buildUrl(path, injectSecurityInfo(new HashMap<>()));
return resultPath; return resultPath;
} }
} }

@ -21,7 +21,7 @@ import cn.hippo4j.common.constant.Constants;
import cn.hippo4j.common.model.TokenInfo; import cn.hippo4j.common.model.TokenInfo;
import cn.hippo4j.common.toolkit.JSONUtil; import cn.hippo4j.common.toolkit.JSONUtil;
import cn.hippo4j.common.toolkit.StringUtil; import cn.hippo4j.common.toolkit.StringUtil;
import cn.hippo4j.common.toolkit.http.HttpUtils; import cn.hippo4j.common.toolkit.http.HttpUtil;
import cn.hippo4j.common.web.base.Result; import cn.hippo4j.common.web.base.Result;
import cn.hippo4j.springboot.starter.config.BootstrapProperties; import cn.hippo4j.springboot.starter.config.BootstrapProperties;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@ -79,7 +79,7 @@ public class SecurityProxy {
bodyMap.put("userName", username); bodyMap.put("userName", username);
bodyMap.put("password", password); bodyMap.put("password", password);
try { try {
Result result = HttpUtils.post(url, bodyMap, Result.class); Result result = HttpUtil.post(url, bodyMap, Result.class);
if (!result.isSuccess()) { if (!result.isSuccess()) {
log.error("Error getting access token. message: {}", result.getMessage()); log.error("Error getting access token. message: {}", result.getMessage());
return false; return false;

Loading…
Cancel
Save