Replace RestTemplate with HttpClientUtil (#791)

* fix : update RestTemplate to HttpClientUtil

* fix : delete httpclient in dependencies
pull/797/head
pizihao 2 years ago committed by GitHub
parent ece1143651
commit 1f4da093b4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -66,5 +66,9 @@
<groupId>com.github.dozermapper</groupId>
<artifactId>dozer-core</artifactId>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
</dependency>
</dependencies>
</project>

@ -15,18 +15,21 @@
* limitations under the License.
*/
package cn.hippo4j.springboot.starter.toolkit;
package cn.hippo4j.common.toolkit;
import cn.hippo4j.common.toolkit.JSONUtil;
import cn.hippo4j.common.web.exception.ServiceException;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
/**
* HttpClient util.
@ -34,13 +37,30 @@ import java.util.concurrent.TimeUnit;
@Slf4j
public class HttpClientUtil {
@Resource
private OkHttpClient hippo4JOkHttpClient;
private static AtomicReference<HttpClientUtil> reference = new AtomicReference<>();
private MediaType jsonMediaType = MediaType.parse("application/json; charset=utf-8");
private static int HTTP_OK_CODE = 200;
private HttpClientUtil() {
OkHttpClient.Builder build = new OkHttpClient.Builder();
build.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
supportHttps(build);
this.hippo4JOkHttpClient = build.build();
}
public static HttpClientUtil build() {
if (reference.get() == null) {
reference.compareAndSet(null, new HttpClientUtil());
}
return reference.get();
}
/**
* Get.
*
@ -170,8 +190,13 @@ public class HttpClientUtil {
@SneakyThrows
private String doPost(String url, Object body) {
String jsonBody = JSONUtil.toJSONString(body);
RequestBody requestBody = RequestBody.create(jsonMediaType, jsonBody);
String bodyContent;
if (body instanceof String) {
bodyContent = (String) body;
} else {
bodyContent = JSONUtil.toJSONString(body);
}
RequestBody requestBody = RequestBody.create(jsonMediaType, bodyContent);
Request request = new Request.Builder()
.url(url)
.post(requestBody)
@ -179,7 +204,7 @@ public class HttpClientUtil {
try (Response resp = hippo4JOkHttpClient.newCall(request).execute()) {
try (ResponseBody responseBody = resp.body()) {
if (resp.code() != HTTP_OK_CODE) {
String msg = String.format("HttpPost response code error. [code] %s [url] %s [body] %s", resp.code(), url, jsonBody);
String msg = String.format("HttpPost response code error. [code] %s [url] %s [body] %s", resp.code(), url, bodyContent);
throw new ServiceException(msg);
}
return responseBody.string();
@ -246,4 +271,29 @@ public class HttpClientUtil {
}
}
}
@SneakyThrows
private void supportHttps(OkHttpClient.Builder builder) {
final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
}};
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
builder.hostnameVerifier((hostname, session) -> true);
}
}

@ -0,0 +1,108 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.hippo4j.common.toolkit;
import lombok.Getter;
import lombok.Setter;
import org.junit.Assert;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
public class HttpClientUtilTest {
/**
* test post url
*/
static String postUrl = "http://console.hippo4j.cn/hippo4j/v1/cs/";
/**
* test get url
*/
static String getUrl = "https://hippo4j.cn/";
HttpClientUtil httpClientUtil = HttpClientUtil.build();
@Test
public void get() {
String s = httpClientUtil.get(getUrl);
Assert.assertNotNull(s);
}
@Test
public void restApiPost() {
String loginUrl = postUrl + "auth/login";
LoginInfo loginInfo = new LoginInfo();
loginInfo.setPassword("hippo4j");
loginInfo.setUsername("hippo4j");
loginInfo.setRememberMe(1);
String s = httpClientUtil.restApiPost(loginUrl, loginInfo);
Result result = JSONUtil.parseObject(s, Result.class);
Assert.assertNotNull(result);
String data = result.getData().getData();
Assert.assertNotNull(data);
}
@Test
public void testRestApiPost() {
String loginUrl = postUrl + "auth/login";
LoginInfo loginInfo = new LoginInfo();
loginInfo.setPassword("hippo4j");
loginInfo.setUsername("hippo4j");
loginInfo.setRememberMe(1);
Result result = httpClientUtil.restApiPost(loginUrl, loginInfo, Result.class);
Assert.assertNotNull(result);
String data = result.getData().getData();
Assert.assertNotNull(data);
}
@Test
public void buildUrl() {
Map<String, String> map = new HashMap<>();
map.put("password", "hippo4j");
map.put("username", "hippo4j");
String s = httpClientUtil.buildUrl(getUrl, map);
Assert.assertEquals(getUrl + "?password=hippo4j&username=hippo4j", s);
}
@Getter
@Setter
private static class LoginInfo {
private String username;
private String password;
private Integer rememberMe;
}
@Getter
@Setter
private static class Result {
private String code;
private ResultData data;
}
@Getter
@Setter
private static class ResultData {
private String data;
private String[] roles;
}
}

@ -60,10 +60,6 @@
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>

@ -23,6 +23,7 @@ import cn.hippo4j.common.design.observer.AbstractSubjectCenter;
import cn.hippo4j.common.design.observer.Observer;
import cn.hippo4j.common.design.observer.ObserverMessage;
import cn.hippo4j.common.toolkit.CollectionUtil;
import cn.hippo4j.common.toolkit.HttpClientUtil;
import cn.hippo4j.common.toolkit.JSONUtil;
import cn.hippo4j.common.toolkit.StringUtil;
import cn.hippo4j.common.web.base.Result;
@ -31,7 +32,6 @@ import cn.hippo4j.config.model.biz.adapter.ThreadPoolAdapterRespDTO;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
@ -46,6 +46,8 @@ import static cn.hippo4j.common.constant.Constants.IDENTIFY_SLICER_SYMBOL;
@Service
public class ThreadPoolAdapterService {
private HttpClientUtil httpClientUtil = HttpClientUtil.build();
/**
* Map&lt;mark, Map&lt;tenantItem, Map&lt;threadPoolKey, List&lt;ThreadPoolAdapterState&gt;&gt;&gt;&gt;
*/
@ -96,23 +98,12 @@ public class ThreadPoolAdapterService {
List<String> addressList = actual.stream().map(ThreadPoolAdapterState::getClientAddress).collect(Collectors.toList());
List<ThreadPoolAdapterRespDTO> result = new ArrayList<>(addressList.size());
addressList.forEach(each -> {
StringBuilder builder = StringUtil.createBuilder("http://", each, "/adapter/thread-pool/info");
Map<String, Object> param = new HashMap<>();
String url = StringUtil.newBuilder("http://", each, "/adapter/thread-pool/info");
Map<String, String> param = new HashMap<>();
param.put("mark", requestParameter.getMark());
param.put("threadPoolKey", requestParameter.getThreadPoolKey());
List<String> paramKey = new ArrayList<>(param.keySet());
for (int i = 0; i < paramKey.size(); i++) {
if (i == 0) {
builder.append("?");
} else {
builder.append("&");
}
String s = paramKey.get(i);
builder.append(StringUtil.newBuilder(s, "={", s, "}"));
}
try {
RestTemplate template = new RestTemplate();
String resultStr = template.getForObject(builder.toString(), String.class, param);
String resultStr = httpClientUtil.get(url, param);
if (StringUtil.isNotBlank(resultStr)) {
Result<ThreadPoolAdapterRespDTO> restResult = JSONUtil.parseObject(resultStr, new TypeReference<Result<ThreadPoolAdapterRespDTO>>() {
});

@ -18,15 +18,11 @@
package cn.hippo4j.config.service.biz.impl;
import cn.hippo4j.common.constant.ConfigModifyTypeConstants;
import cn.hippo4j.common.toolkit.JSONUtil;
import cn.hippo4j.common.toolkit.HttpClientUtil;
import cn.hippo4j.common.toolkit.StringUtil;
import cn.hippo4j.config.model.biz.threadpool.ConfigModifyVerifyReqDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
/**
* Adapter thread pool config modification verify service impl.
@ -35,7 +31,7 @@ import org.springframework.web.client.RestTemplate;
@Service
public class AdapterThreadPoolConfigModificationVerifyServiceImpl extends AbstractConfigModificationVerifyService {
private final RestTemplate restTemplate = new RestTemplate();
private final HttpClientUtil httpClientUtil = HttpClientUtil.build();
@Override
public Integer type() {
@ -46,11 +42,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");
// again appoint MediaType
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> requestEntity = new HttpEntity<>(JSONUtil.toJSONString(reqDTO), requestHeaders);
restTemplate.postForObject(urlString, requestEntity, Object.class);
httpClientUtil.restApiPost(urlString, reqDTO, Object.class);
}
}
}

@ -18,15 +18,11 @@
package cn.hippo4j.config.service.biz.impl;
import cn.hippo4j.common.constant.ConfigModifyTypeConstants;
import cn.hippo4j.common.toolkit.JSONUtil;
import cn.hippo4j.common.toolkit.HttpClientUtil;
import cn.hippo4j.common.toolkit.StringUtil;
import cn.hippo4j.config.model.biz.threadpool.ConfigModifyVerifyReqDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
/**
* Web thread pool config modification verify service impl.
@ -35,7 +31,7 @@ import org.springframework.web.client.RestTemplate;
@Service
public class WebThreadPoolConfigModificationVerifyServiceImpl extends AbstractConfigModificationVerifyService {
private final RestTemplate restTemplate = new RestTemplate();
private final HttpClientUtil httpClientUtil = HttpClientUtil.build();
@Override
public Integer type() {
@ -46,11 +42,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");
// again appoint MediaType
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> requestEntity = new HttpEntity<>(JSONUtil.toJSONString(reqDTO), requestHeaders);
restTemplate.postForObject(urlString, requestEntity, Object.class);
httpClientUtil.restApiPost(urlString, reqDTO, Object.class);
}
}
}

@ -18,10 +18,7 @@
package cn.hippo4j.console.controller;
import cn.hippo4j.common.constant.ConfigModifyTypeConstants;
import cn.hippo4j.common.toolkit.BeanUtil;
import cn.hippo4j.common.toolkit.JSONUtil;
import cn.hippo4j.common.toolkit.UserContext;
import cn.hippo4j.common.toolkit.StringUtil;
import cn.hippo4j.common.toolkit.*;
import cn.hippo4j.common.web.base.Result;
import cn.hippo4j.common.web.base.Results;
import cn.hippo4j.config.model.biz.adapter.ThreadPoolAdapterReqDTO;
@ -29,15 +26,11 @@ import cn.hippo4j.config.model.biz.adapter.ThreadPoolAdapterRespDTO;
import cn.hippo4j.config.model.biz.threadpool.ConfigModifySaveReqDTO;
import cn.hippo4j.config.service.ThreadPoolAdapterService;
import cn.hippo4j.config.verify.ConfigModificationVerifyServiceChoose;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.List;
import java.util.Set;
@ -47,7 +40,7 @@ import static cn.hippo4j.common.constant.Constants.REGISTER_ADAPTER_BASE_PATH;
/**
* Thread-pool adapter controller.
*/
@AllArgsConstructor
@RequiredArgsConstructor
@RestController("threadPoolAdapterConsoleController")
public class ThreadPoolAdapterController {
@ -55,6 +48,8 @@ public class ThreadPoolAdapterController {
private final ConfigModificationVerifyServiceChoose configModificationVerifyServiceChoose;
private HttpClientUtil httpClientUtil = HttpClientUtil.build();
@GetMapping(REGISTER_ADAPTER_BASE_PATH + "/query")
public Result<List<ThreadPoolAdapterRespDTO>> queryAdapterThreadPool(ThreadPoolAdapterReqDTO requestParameter) {
List<ThreadPoolAdapterRespDTO> result = threadPoolAdapterService.query(requestParameter);
@ -72,12 +67,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");
RestTemplate restTemplate = new RestTemplate();
// again appoint MediaType
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> requestEntity = new HttpEntity<>(JSONUtil.toJSONString(requestParameter), requestHeaders);
restTemplate.postForObject(urlString, requestEntity, Object.class);
httpClientUtil.restApiPost(urlString, requestParameter, Object.class);
}
} else {
ConfigModifySaveReqDTO modifySaveReqDTO = BeanUtil.convert(requestParameter, ConfigModifySaveReqDTO.class);

@ -35,16 +35,11 @@ import cn.hippo4j.console.model.WebThreadPoolRespDTO;
import cn.hippo4j.discovery.core.BaseInstanceRegistry;
import cn.hippo4j.discovery.core.Lease;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@ -55,7 +50,7 @@ import static cn.hippo4j.common.toolkit.ContentUtil.getGroupKey;
* Thread pool controller.
*/
@RestController
@AllArgsConstructor
@RequiredArgsConstructor
@RequestMapping(Constants.BASE_PATH + "/thread/pool")
public class ThreadPoolController {
@ -65,6 +60,10 @@ public class ThreadPoolController {
private final ConfigModificationVerifyServiceChoose configModificationVerifyServiceChoose;
private HttpClientUtil httpClientUtil = HttpClientUtil.build();
private static final String HTTP = "http://";
@PostMapping("/query/page")
public Result<IPage<ThreadPoolRespDTO>> queryNameSpacePage(@RequestBody ThreadPoolQueryReqDTO reqDTO) {
return Results.success(threadPoolService.queryThreadPoolPage(reqDTO));
@ -110,21 +109,15 @@ public class ThreadPoolController {
@GetMapping("/run/state/{tpId}")
public Result runState(@PathVariable("tpId") String tpId,
@RequestParam(value = "clientAddress") String clientAddress) {
String urlString = StringUtil.newBuilder("http://", clientAddress, "/run/state/", tpId);
RestTemplate restTemplate = new RestTemplate();
String data = restTemplate.getForObject(urlString, String.class, new HashMap<>());
Result result = JSONUtil.parseObject(data, Result.class);
return result;
String urlString = StringUtil.newBuilder(HTTP, clientAddress, "/run/state/", tpId);
return httpClientUtil.restApiGet(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);
RestTemplate restTemplate = new RestTemplate();
String data = restTemplate.getForObject(urlString, String.class, new HashMap<>());
Result result = JSONUtil.parseObject(data, Result.class);
return result;
String urlString = StringUtil.newBuilder(HTTP, clientAddress, "/run/thread/state/", tpId);
return httpClientUtil.restApiGet(urlString, Result.class);
}
@GetMapping("/list/client/instance/{itemId}")
@ -159,33 +152,22 @@ public class ThreadPoolController {
@GetMapping("/web/base/info")
public Result getPoolBaseState(@RequestParam(value = "clientAddress") String clientAddress) {
String urlString = StringUtil.newBuilder("http://", clientAddress, "/web/base/info");
RestTemplate restTemplate = new RestTemplate();
String data = restTemplate.getForObject(urlString, String.class, new HashMap<>());
Result result = JSONUtil.parseObject(data, Result.class);
return result;
String urlString = StringUtil.newBuilder(HTTP, clientAddress, "/web/base/info");
return httpClientUtil.restApiGet(urlString, Result.class);
}
@GetMapping("/web/run/state")
public Result getPoolRunState(@RequestParam(value = "clientAddress") String clientAddress) {
String urlString = StringUtil.newBuilder("http://", clientAddress, "/web/run/state");
RestTemplate restTemplate = new RestTemplate();
String data = restTemplate.getForObject(urlString, String.class, new HashMap<>());
Result result = JSONUtil.parseObject(data, Result.class);
return result;
String urlString = StringUtil.newBuilder(HTTP, clientAddress, "/web/run/state");
return httpClientUtil.restApiGet(urlString, Result.class);
}
@PostMapping("/web/update/pool")
public Result<Void> updateWebThreadPool(@RequestBody WebThreadPoolReqDTO requestParam) {
if (UserContext.getUserRole().equals("ROLE_ADMIN")) {
for (String each : requestParam.getClientAddressList()) {
String urlString = StringUtil.newBuilder("http://", each, "/web/update/pool");
RestTemplate restTemplate = new RestTemplate();
// again appoint MediaType
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> requestEntity = new HttpEntity<>(JSONUtil.toJSONString(requestParam), requestHeaders);
restTemplate.postForObject(urlString, requestEntity, Object.class);
String urlString = StringUtil.newBuilder(HTTP, each, "/web/update/pool");
httpClientUtil.restApiPost(urlString, requestParam, Object.class);
}
} else {
ConfigModifySaveReqDTO modifySaveReqDTO = BeanUtil.convert(requestParam, ConfigModifySaveReqDTO.class);

@ -17,6 +17,7 @@
package cn.hippo4j.message.platform;
import cn.hippo4j.common.toolkit.HttpClientUtil;
import cn.hippo4j.common.toolkit.Singleton;
import cn.hippo4j.message.dto.NotifyConfigDTO;
import cn.hippo4j.message.enums.NotifyPlatformEnum;
@ -26,11 +27,9 @@ import cn.hippo4j.message.request.AlarmNotifyRequest;
import cn.hippo4j.message.request.ChangeParameterNotifyRequest;
import cn.hippo4j.common.toolkit.StringUtil;
import cn.hippo4j.common.toolkit.FileUtil;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@ -44,9 +43,11 @@ import static cn.hippo4j.message.platform.constant.LarkAlarmConstants.*;
* Send lark notification message.
*/
@Slf4j
@AllArgsConstructor
@RequiredArgsConstructor
public class LarkSendMessageHandler implements SendMessageHandler<AlarmNotifyRequest, ChangeParameterNotifyRequest> {
private HttpClientUtil httpClientUtil = HttpClientUtil.build();
@Override
public String getType() {
return NotifyPlatformEnum.LARK.name();
@ -173,8 +174,7 @@ public class LarkSendMessageHandler implements SendMessageHandler<AlarmNotifyReq
private void execute(String secretKey, String text) {
String serverUrl = LARK_BOT_URL + secretKey;
try {
RestTemplate template = new RestTemplate();
template.postForObject(serverUrl, text, Object.class);
httpClientUtil.restApiPost(serverUrl, text, Object.class);
} catch (Exception ex) {
log.error("Lark failed to send message", ex);
}

@ -18,6 +18,7 @@
package cn.hippo4j.message.platform;
import cn.hippo4j.common.toolkit.FileUtil;
import cn.hippo4j.common.toolkit.HttpClientUtil;
import cn.hippo4j.common.toolkit.Singleton;
import cn.hippo4j.message.enums.NotifyPlatformEnum;
import cn.hippo4j.message.platform.base.AbstractRobotSendMessageHandler;
@ -26,7 +27,6 @@ import cn.hippo4j.message.platform.base.RobotMessageExecuteDTO;
import lombok.Data;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.client.RestTemplate;
import static cn.hippo4j.message.platform.constant.WeChatAlarmConstants.*;
@ -36,6 +36,8 @@ import static cn.hippo4j.message.platform.constant.WeChatAlarmConstants.*;
@Slf4j
public class WeChatSendMessageHandler extends AbstractRobotSendMessageHandler {
private final HttpClientUtil httpClientUtil = HttpClientUtil.build();
@Override
public String getType() {
return NotifyPlatformEnum.WECHAT.name();
@ -64,8 +66,7 @@ public class WeChatSendMessageHandler extends AbstractRobotSendMessageHandler {
Markdown markdown = new Markdown();
markdown.setContent(robotMessageExecuteDTO.getText());
weChatReq.setMarkdown(markdown);
RestTemplate template = new RestTemplate();
template.postForObject(serverUrl, weChatReq, Object.class);
httpClientUtil.restApiPost(serverUrl, weChatReq, Object.class);
} catch (Exception ex) {
log.error("WeChat failed to send message", ex);
}

@ -21,11 +21,6 @@
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
</dependency>
<dependency>
<groupId>cn.hippo4j</groupId>
<artifactId>hippo4j-core</artifactId>

@ -17,37 +17,19 @@
package cn.hippo4j.springboot.starter.config;
import cn.hippo4j.springboot.starter.toolkit.HttpClientUtil;
import cn.hippo4j.common.toolkit.HttpClientUtil;
import cn.hippo4j.springboot.starter.remote.HttpAgent;
import cn.hippo4j.springboot.starter.remote.ServerHttpAgent;
import lombok.SneakyThrows;
import okhttp3.OkHttpClient;
import org.springframework.context.annotation.Bean;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.util.concurrent.TimeUnit;
/**
* Http client config.
*/
public class HttpClientConfiguration {
@Bean
public OkHttpClient hippo4JOkHttpClient() {
OkHttpClient.Builder build = new OkHttpClient.Builder();
build.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
supportHttps(build);
return build.build();
}
@Bean
public HttpClientUtil hippo4JHttpClientUtil() {
return new HttpClientUtil();
return HttpClientUtil.build();
}
@Bean
@ -55,29 +37,4 @@ public class HttpClientConfiguration {
public HttpAgent httpAgent(BootstrapProperties properties, HttpClientUtil hippo4JHttpClientUtil) {
return new ServerHttpAgent(properties, hippo4JHttpClientUtil);
}
@SneakyThrows
private void supportHttps(OkHttpClient.Builder builder) {
final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
}};
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
builder.hostnameVerifier((hostname, session) -> true);
}
}

@ -24,7 +24,7 @@ import cn.hippo4j.common.web.base.Result;
import cn.hippo4j.common.design.builder.ThreadFactoryBuilder;
import cn.hippo4j.springboot.starter.config.BootstrapProperties;
import cn.hippo4j.springboot.starter.security.SecurityProxy;
import cn.hippo4j.springboot.starter.toolkit.HttpClientUtil;
import cn.hippo4j.common.toolkit.HttpClientUtil;
import java.util.HashMap;
import java.util.Map;

@ -23,7 +23,7 @@ import cn.hippo4j.common.toolkit.JSONUtil;
import cn.hippo4j.common.toolkit.StringUtil;
import cn.hippo4j.common.web.base.Result;
import cn.hippo4j.springboot.starter.config.BootstrapProperties;
import cn.hippo4j.springboot.starter.toolkit.HttpClientUtil;
import cn.hippo4j.common.toolkit.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import java.util.HashMap;

Loading…
Cancel
Save