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);
/**
* validate Json.
* Validate json.
*
* @param text
* @return
*/

@ -18,20 +18,29 @@
package cn.hippo4j.common.constant;
/**
* header constants.
* Http header constants.
*/
public interface HttpHeaderConsts {
public interface HttpHeaderConstants {
String CLIENT_VERSION_HEADER = "Client-Version";
String USER_AGENT_HEADER = "User-Agent";
String REQUEST_SOURCE_HEADER = "Request-Source";
String CONTENT_TYPE = "Content-Type";
String CONTENT_LENGTH = "Content-Length";
String ACCEPT_CHARSET = "Accept-Charset";
String ACCEPT_ENCODING = "Accept-Encoding";
String CONTENT_ENCODING = "Content-Encoding";
String CONNECTION = "Requester";
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;
/**
* Http Media types.
* Http media type.
*
* @author Rongzhen Yan
*/
@ -85,7 +85,7 @@ public final class HttpMediaType {
* Use the given contentType and charset to assemble into a {@code MediaType} object.
*
* @param contentType contentType
* @param charset charset
* @param charset charset
* @return MediaType
*/
public static HttpMediaType valueOf(String contentType, String charset) {

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

@ -34,7 +34,7 @@ import java.util.zip.GZIPOutputStream;
*
* @author nacos
*/
public class IoUtils {
public class IoUtil {
/**
* Try decompress by GZIP from stream.
@ -173,7 +173,7 @@ public class IoUtils {
public static long copy(Reader input, Writer output) throws IOException {
char[] buffer = new char[1 << 12];
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);
count += n;
}
@ -336,6 +336,6 @@ public class IoUtils {
}
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 {
MAPPER.readTree(text);
return true;
} catch (JsonProcessingException jpe) {
return false;
} catch (JsonProcessingException ignored) {
}
return false;
}
}

@ -25,7 +25,7 @@ import java.util.function.BiFunction;
import java.util.function.Predicate;
/**
* Map utils.
* Map util.
*/
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,
T param2) {
Objects.requireNonNull(target, "target");
Objects.requireNonNull(key, "key");
Objects.requireNonNull(mappingFunction, "mappingFunction");
Objects.requireNonNull(param1, "param1");
Objects.requireNonNull(param2, "param2");
V val = target.get(key);
if (val == null) {
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.
*
* @param map map
* @param key key
* @param map map
* @param key key
* @param removeJudge judge this key can be remove
* @param <K> key type
* @param <V> value type
* @param <K> key type
* @param <V> value type
* @return value
*/
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;
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.toolkit.MapUtil;
import cn.hippo4j.common.toolkit.StringUtil;
@ -45,9 +45,8 @@ public class Header {
private Header() {
header = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
originalResponseHeader = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
addParam(HttpHeaderConsts.CONTENT_TYPE, HttpMediaType.APPLICATION_JSON);
addParam(HttpHeaderConsts.ACCEPT_CHARSET, DEFAULT_CHARSET);
// addParam(HttpHeaderConsts.ACCEPT_ENCODING, DEFAULT_ENCODING);
addParam(HttpHeaderConstants.CONTENT_TYPE, HttpMediaType.APPLICATION_JSON);
addParam(HttpHeaderConstants.ACCEPT_CHARSET, DEFAULT_CHARSET);
}
public static Header newInstance() {
@ -57,7 +56,7 @@ public class Header {
/**
* Add the key and value to the header.
*
* @param key the key
* @param key the key
* @param value the value
* @return header
*/
@ -72,7 +71,7 @@ public class Header {
if (contentType == null) {
contentType = HttpMediaType.APPLICATION_JSON;
}
return addParam(HttpHeaderConsts.CONTENT_TYPE, contentType);
return addParam(HttpHeaderConstants.CONTENT_TYPE, contentType);
}
public Header build() {
@ -144,7 +143,7 @@ public class Header {
*
* <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
*/
public void addOriginalResponseHeader(String key, List<String> values) {
@ -166,9 +165,9 @@ public class Header {
}
public String getCharset() {
String acceptCharset = getValue(HttpHeaderConsts.ACCEPT_CHARSET);
String acceptCharset = getValue(HttpHeaderConstants.ACCEPT_CHARSET);
if (acceptCharset == null) {
String contentType = getValue(HttpHeaderConsts.CONTENT_TYPE);
String contentType = getValue(HttpHeaderConstants.CONTENT_TYPE);
acceptCharset = StringUtil.isNotBlank(contentType) ? analysisCharset(contentType) : Constants.ENCODE;
}
return acceptCharset;

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

@ -21,106 +21,224 @@ import cn.hippo4j.common.constant.Constants;
import cn.hippo4j.common.constant.HttpMediaType;
import cn.hippo4j.common.constant.HttpMethod;
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.StringUtil;
import cn.hippo4j.common.toolkit.logtracing.LogMessage;
import cn.hippo4j.common.web.exception.ServiceException;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
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.
*
* @author Rongzhen Yan
*/
@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) {
String result = post(url, body);
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);
}
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();
return JSONUtil.parseObject(result, clazz);
/**
* Send a post 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 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();
return JSONUtil.parseObject(result, clazz);
/**
* Send a post network request.
*
* @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) {
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) {
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) {
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) {
return execute(url, HttpMethod.PUT, body, headers).getBodyString();
}
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);
return execute(url, HttpMethod.PUT, body, headers);
}
/**
* Constructs a complete Url from the query string.
* @param url
* @param queryString
*
* @param url target url
* @param queryParams query params
* @return
*/
@SneakyThrows
public static String buildUrl(String url, Map<String, String> queryString) {
if (null == queryString) {
public static String buildUrl(String url, Map<String, String> queryParams) {
if (CollectionUtil.isEmpty(queryParams)) {
return url;
}
StringBuilder builder = new StringBuilder(url);
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();
if (key != null && entry.getValue() != null) {
if (isFirst) {
@ -129,7 +247,7 @@ public class HttpUtils {
} else {
builder.append("&");
}
String value = URLEncoder.encode(queryString.get(key), Constants.ENCODE)
String value = URLEncoder.encode(queryParams.get(key), Constants.ENCODE)
.replaceAll("\\+", "%20");
builder.append(key)
.append("=")
@ -139,17 +257,49 @@ public class HttpUtils {
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);
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
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 {
if (headers != null) {
for (String key : headers.keySet()) {
connection.setRequestProperty(key, headers.get(key));
if (headers != null && headers.size() > 0) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
}
String bodyString;
@ -165,7 +315,7 @@ public class HttpUtils {
OutputStream outputStream = connection.getOutputStream();
outputStream.write(b, 0, b.length);
outputStream.flush();
IoUtils.closeQuietly(outputStream);
IoUtil.closeQuietly(outputStream);
}
connection.connect();
JdkHttpClientResponse response = new JdkHttpClientResponse(connection);
@ -174,31 +324,14 @@ public class HttpUtils {
throw new ServiceException(msg);
}
return response;
} catch (Throwable e) {
log.error(LogMessage.getInstance().setMsg("Http Call error.")
} catch (Throwable ex) {
log.error(LogMessage.getInstance().setMsg("Http call error. ")
.kv("url", connection.getURL())
.kv("method", connection.getRequestMethod())
.kv("body", JSONUtil.toJSONString(body))
.kv2String("headers", JSONUtil.toJSONString(headers)), e);
throw e;
}
}
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.");
.kv2String("headers", JSONUtil.toJSONString(headers)), ex);
throw ex;
}
return execute(url, method, json, headers);
}
@SneakyThrows
@ -206,8 +339,8 @@ public class HttpUtils {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setConnectTimeout(CONNECT_TIMEOUT);
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT);
connection.setReadTimeout(DEFAULT_READ_TIMEOUT);
connection.setRequestMethod(method);
connection.setRequestProperty(Constants.CONTENT_TYPE, HttpMediaType.APPLICATION_JSON);
return connection;
@ -216,7 +349,6 @@ public class HttpUtils {
@SneakyThrows
private static HttpURLConnection createConnection(String url, String method, long timeout) {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setConnectTimeout(Integer.parseInt(String.valueOf(timeout)));

@ -18,8 +18,8 @@
package cn.hippo4j.common.toolkit.http;
import cn.hippo4j.common.constant.Constants;
import cn.hippo4j.common.constant.HttpHeaderConsts;
import cn.hippo4j.common.toolkit.IoUtils;
import cn.hippo4j.common.constant.HttpHeaderConstants;
import cn.hippo4j.common.toolkit.IoUtil;
import lombok.SneakyThrows;
import java.io.ByteArrayInputStream;
@ -64,10 +64,10 @@ public class JdkHttpClientResponse implements HttpClientResponse {
Header headers = getHeaders();
InputStream errorStream = this.conn.getErrorStream();
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
if (CONTENT_ENCODING.equals(contentEncoding)) {
byte[] bytes = IoUtils.tryDecompress(this.responseStream);
byte[] bytes = IoUtil.tryDecompress(this.responseStream);
return new ByteArrayInputStream(bytes);
}
return this.responseStream;
@ -87,11 +87,11 @@ public class JdkHttpClientResponse implements HttpClientResponse {
@Override
public String getBodyString() {
return IoUtils.toString(this.getBody(), Constants.ENCODE);
return IoUtil.toString(this.getBody(), Constants.ENCODE);
}
@Override
public void close() {
IoUtils.closeQuietly(this.responseStream);
IoUtil.closeQuietly(this.responseStream);
}
}

@ -17,6 +17,9 @@
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.MessageFormatter;
@ -24,16 +27,16 @@ import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* KV
* Log message.
*
* @author Rongzhen Yan
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class LogMessage {
private Map<String, Object> kvs = new ConcurrentHashMap<>();
private String msg = "";
private LogMessage() {
}
private String msg = "";
public static LogMessage getInstance() {
return new LogMessage();
@ -75,16 +78,23 @@ public class LogMessage {
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (msg != null && !msg.isEmpty()) {
sb.append("||_msg=").append(msg);
if (StringUtil.isNotEmpty(msg)) {
sb.append(msg);
}
int tempCount = 0;
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();
}
}

@ -41,7 +41,7 @@ public class HttpUtilsTest {
@Test
public void get() {
String s = HttpUtils.get(getUrl);
String s = HttpUtil.get(getUrl);
Assert.assertNotNull(s);
}
@ -52,7 +52,7 @@ public class HttpUtilsTest {
loginInfo.setPassword("hippo4j");
loginInfo.setUsername("hippo4j");
loginInfo.setRememberMe(1);
String s = HttpUtils.post(loginUrl, loginInfo);
String s = HttpUtil.post(loginUrl, loginInfo);
Result result = JSONUtil.parseObject(s, Result.class);
Assert.assertNotNull(result);
String data = result.getData().getData();
@ -66,7 +66,7 @@ public class HttpUtilsTest {
loginInfo.setPassword("hippo4j");
loginInfo.setUsername("hippo4j");
loginInfo.setRememberMe(1);
Result result = HttpUtils.post(loginUrl, loginInfo, Result.class);
Result result = HttpUtil.post(loginUrl, loginInfo, Result.class);
Assert.assertNotNull(result);
String data = result.getData().getData();
Assert.assertNotNull(data);
@ -79,7 +79,7 @@ public class HttpUtilsTest {
loginInfo.setPassword("hippo4j");
loginInfo.setUsername("hippo4j");
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
@ -87,7 +87,7 @@ public class HttpUtilsTest {
Map<String, String> map = new HashMap<>();
map.put("password", "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);
}
@ -96,7 +96,9 @@ public class HttpUtilsTest {
private static class LoginInfo {
private String username;
private String password;
private Integer rememberMe;
}
@ -105,6 +107,7 @@ public class HttpUtilsTest {
private static class Result {
private String code;
private ResultData data;
}
@ -113,6 +116,7 @@ public class HttpUtilsTest {
private static class ResultData {
private String data;
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.JSONUtil;
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.config.model.biz.adapter.ThreadPoolAdapterReqDTO;
import cn.hippo4j.config.model.biz.adapter.ThreadPoolAdapterRespDTO;
@ -101,7 +101,7 @@ public class ThreadPoolAdapterService {
param.put("mark", requestParameter.getMark());
param.put("threadPoolKey", requestParameter.getThreadPoolKey());
try {
String resultStr = HttpUtils.get(url, param);
String resultStr = HttpUtil.get(url, param);
if (StringUtil.isNotBlank(resultStr)) {
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.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 lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@ -40,7 +40,7 @@ public class AdapterThreadPoolConfigModificationVerifyServiceImpl extends Abstra
protected void updateThreadPoolParameter(ConfigModifyVerifyReqDTO reqDTO) {
for (String each : getClientAddress(reqDTO)) {
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.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 lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@ -40,7 +40,7 @@ public class WebThreadPoolConfigModificationVerifyServiceImpl extends AbstractCo
protected void updateThreadPoolParameter(ConfigModifyVerifyReqDTO reqDTO) {
for (String each : getClientAddress(reqDTO)) {
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.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.Results;
import cn.hippo4j.config.model.biz.adapter.ThreadPoolAdapterReqDTO;
@ -66,7 +66,7 @@ public class ThreadPoolAdapterController {
if (UserContext.getUserRole().equals("ROLE_ADMIN")) {
for (String each : requestParameter.getClientAddressList()) {
String urlString = StringUtil.newBuilder("http://", each, "/adapter/thread-pool/update");
HttpUtils.post(urlString, requestParameter);
HttpUtil.post(urlString, requestParameter);
}
} else {
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.model.InstanceInfo;
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.Results;
import cn.hippo4j.common.web.exception.ErrorCodeEnum;
@ -109,14 +109,14 @@ public class ThreadPoolController {
public Result runState(@PathVariable("tpId") String tpId,
@RequestParam(value = "clientAddress") String clientAddress) {
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}")
public Result runThreadState(@PathVariable("tpId") String tpId,
@RequestParam(value = "clientAddress") String clientAddress) {
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}")
@ -152,13 +152,13 @@ public class ThreadPoolController {
@GetMapping("/web/base/info")
public Result getPoolBaseState(@RequestParam(value = "clientAddress") String clientAddress) {
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")
public Result getPoolRunState(@RequestParam(value = "clientAddress") String clientAddress) {
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")
@ -166,7 +166,7 @@ public class ThreadPoolController {
if (UserContext.getUserRole().equals("ROLE_ADMIN")) {
for (String each : requestParam.getClientAddressList()) {
String urlString = StringUtil.newBuilder(HTTP, each, "/web/update/pool");
HttpUtils.post(urlString, requestParam);
HttpUtil.post(urlString, requestParam);
}
} else {
ConfigModifySaveReqDTO modifySaveReqDTO = BeanUtil.convert(requestParam, ConfigModifySaveReqDTO.class);

@ -18,7 +18,7 @@
package cn.hippo4j.message.platform;
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.enums.NotifyPlatformEnum;
import cn.hippo4j.message.enums.NotifyTypeEnum;
@ -75,7 +75,6 @@ public class LarkSendMessageHandler implements SendMessageHandler<AlarmNotifyReq
} else {
larkAlarmTxt = StringUtil.replace(larkAlarmTxt, larkAlarmTimoutReplaceJson, "");
}
String text = String.format(larkAlarmTxt,
// 环境
alarmNotifyRequest.getActive(),
@ -172,7 +171,7 @@ public class LarkSendMessageHandler implements SendMessageHandler<AlarmNotifyReq
private void execute(String secretKey, String text) {
String serverUrl = LARK_BOT_URL + secretKey;
try {
HttpUtils.postJson(serverUrl, text);
HttpUtil.postJson(serverUrl, text);
} catch (Exception 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.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.platform.base.AbstractRobotSendMessageHandler;
import cn.hippo4j.message.platform.base.RobotMessageActualContent;
@ -64,8 +64,7 @@ public class WeChatSendMessageHandler extends AbstractRobotSendMessageHandler {
Markdown markdown = new Markdown();
markdown.setContent(robotMessageExecuteDTO.getText());
weChatReq.setMarkdown(markdown);
HttpUtils.post(serverUrl, weChatReq);
HttpUtil.post(serverUrl, weChatReq);
} catch (Exception ex) {
log.error("WeChat failed to send message", ex);
}

@ -158,7 +158,7 @@ public class ClientWorker {
headers.put(LONG_PULLING_TIMEOUT, "" + timeout);
// Confirm the identity of the client, and can be modified separately when modifying the thread pool configuration.
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) {
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.constant.Constants;
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.design.builder.ThreadFactoryBuilder;
import cn.hippo4j.springboot.starter.config.BootstrapProperties;
@ -82,35 +82,35 @@ public class ServerHttpAgent implements HttpAgent {
@Override
public Result httpGetSimple(String path) {
path = injectSecurityInfoByPath(path);
return HttpUtils.get(buildUrl(path), Result.class);
return HttpUtil.get(buildUrl(path), Result.class);
}
@Override
public Result httpPost(String path, Object body) {
isHealthStatus();
path = injectSecurityInfoByPath(path);
return HttpUtils.post(buildUrl(path), body, Result.class);
return HttpUtil.post(buildUrl(path), body, Result.class);
}
@Override
public Result httpPostByDiscovery(String path, Object body) {
isHealthStatus();
path = injectSecurityInfoByPath(path);
return HttpUtils.post(buildUrl(path), body, Result.class);
return HttpUtil.post(buildUrl(path), body, Result.class);
}
@Override
public Result httpGetByConfig(String path, Map<String, String> headers, Map<String, String> paramValues, long readTimeoutMs) {
isHealthStatus();
injectSecurityInfo(paramValues);
return HttpUtils.get(buildUrl(path), headers, paramValues, readTimeoutMs, Result.class);
return HttpUtil.get(buildUrl(path), headers, paramValues, readTimeoutMs, Result.class);
}
@Override
public Result httpPostByConfig(String path, Map<String, String> headers, Map<String, String> paramValues, long readTimeoutMs) {
isHealthStatus();
injectSecurityInfo(paramValues);
return HttpUtils.post(buildUrl(path), headers, paramValues, readTimeoutMs, Result.class);
return HttpUtil.post(buildUrl(path), headers, paramValues, readTimeoutMs, Result.class);
}
@Override
@ -138,7 +138,7 @@ public class ServerHttpAgent implements HttpAgent {
@Deprecated
private String injectSecurityInfoByPath(String path) {
String resultPath = HttpUtils.buildUrl(path, injectSecurityInfo(new HashMap<>()));
String resultPath = HttpUtil.buildUrl(path, injectSecurityInfo(new HashMap<>()));
return resultPath;
}
}

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

Loading…
Cancel
Save