使用OkHttp3替换HttpClient

This commit is contained in:
椰子 2022-08-21 23:48:58 +08:00
parent ef85b53283
commit 3600c0980e
12 changed files with 136 additions and 159 deletions

View File

@ -31,7 +31,6 @@
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>

View File

@ -29,8 +29,8 @@
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
</dependency>
</dependencies>

View File

@ -1,29 +1,17 @@
package com.simaek.notify.dingtalk;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.simaek.notify.DefaultNotifyType;
import com.simaek.notify.Notifier;
import com.simaek.notify.NotifyType;
import com.simaek.notify.Provider;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import okhttp3.*;
import java.io.IOException;
import java.net.URISyntaxException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
public class DingTalkNotifier implements Notifier<DingTalkMessageTemplate> {
@ -42,6 +30,8 @@ public class DingTalkNotifier implements Notifier<DingTalkMessageTemplate> {
private final String notifierId;
private final OkHttpClient httpClient;
@Override
public String getNotifierId() {
return notifierId;
@ -50,6 +40,7 @@ public class DingTalkNotifier implements Notifier<DingTalkMessageTemplate> {
public DingTalkNotifier(String id, DingTalkProperties properties) {
this.properties = properties;
this.notifierId = id;
this.httpClient = new OkHttpClient.Builder().build();
}
@Override
@ -64,29 +55,29 @@ public class DingTalkNotifier implements Notifier<DingTalkMessageTemplate> {
@Override
public void send(DingTalkMessageTemplate template, Map<String, Object> context) {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("access_token", getToken()));
try {
HttpPost httpPost = new HttpPost(new URIBuilder(notifyApi).setParameters(params).build());
HttpUrl url = Objects.requireNonNull(HttpUrl.parse(notifyApi)).newBuilder()
.addQueryParameter("access_token", getToken())
.build();
String formInserter = template.createFormInserter(context);
StringEntity entity = new StringEntity(template.createFormInserter(context));
httpPost.setEntity(entity);
CloseableHttpResponse response = httpClient.execute(httpPost);
JSONObject responseJson = JSON.parseObject(EntityUtils.toString(response.getEntity()));
System.out.println(responseJson);
} catch (URISyntaxException | IOException e) {
RequestBody requestBody = RequestBody.create(formInserter, MediaType.get("application/json"));
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
Call call = httpClient.newCall(request);
try {
Response response = call.execute();
checkResult(Objects.requireNonNull(response.body()).string());
} catch (IOException e) {
e.printStackTrace();
}
}
private void checkResult(String msg) {
if ("0".equals(msg)) {
// log.info("发送钉钉通知成功");
} else {
// log.warn("发送钉钉通知失败:{}", map);
// throw new BusinessException("发送钉钉通知失败:" + map.get("errmsg"), code);
JSONObject jsonObject = JSON.parseObject(msg);
int errorCode = jsonObject.getIntValue("errcode");
if (errorCode != 0) {
throw new RuntimeException("发送钉钉通知失败:" + jsonObject.get("errmsg"));
}
}
@ -98,23 +89,26 @@ public class DingTalkNotifier implements Notifier<DingTalkMessageTemplate> {
}
private String requestToken() {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("appkey", properties.getAppKey()));
params.add(new BasicNameValuePair("appsecret", properties.getAppSecret()));
HttpUrl.Builder urlBuilder = Objects.requireNonNull(HttpUrl.parse(tokenApi)).newBuilder();
urlBuilder.addQueryParameter("appkey", properties.getAppKey());
urlBuilder.addQueryParameter("appsecret", properties.getAppSecret());
Request request = new Request.Builder()
.url(urlBuilder.build())
.get()
.build();
Call call = httpClient.newCall(request);
try {
HttpGet httpGet = new HttpGet(new URIBuilder(tokenApi).setParameters(params).build());
CloseableHttpResponse response = httpClient.execute(httpGet);
JSONObject responseJson = JSON.parseObject(EntityUtils.toString(response.getEntity()));
Response response = call.execute();
JSONObject responseJson = JSON.parseObject(Objects.requireNonNull(response.body()).string());
if (responseJson.containsKey("access_token")) {
String access_token = responseJson.get("access_token").toString();
refreshTokenTime = System.currentTimeMillis();
accessToken.set(access_token);
return access_token;
} else {
// throw new BusinessException("获取Token失败:" + map.get("errmsg"), String.valueOf(map.get("errcode")));
throw new RuntimeException("获取Token失败:" + responseJson.get("errmsg"));
}
} catch (URISyntaxException | IOException e) {
} catch (IOException e) {
e.printStackTrace();
}
return null;

View File

@ -40,8 +40,8 @@
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
</dependency>
<dependency>

View File

@ -7,11 +7,10 @@ import com.simaek.notify.email.EmailTemplate;
import com.simaek.notify.email.EmailTemplateParsed;
import com.simaek.notify.util.ExpressionUtils;
import com.simaek.notify.util.StringUtils;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
@ -57,6 +56,8 @@ public class DefaultEmailNotifier implements Notifier<EmailTemplate> {
private final String notifierId;
private final OkHttpClient httpClient;
@Override
public String getNotifierId() {
return notifierId;
@ -75,6 +76,7 @@ public class DefaultEmailNotifier implements Notifier<EmailTemplate> {
mailSender.setJavaMailProperties(emailProperties.createJavaMailProperties());
this.sender = emailProperties.getSender();
this.javaMailSender = mailSender;
this.httpClient = new OkHttpClient.Builder().build();
}
@Override
@ -124,12 +126,15 @@ public class DefaultEmailNotifier implements Notifier<EmailTemplate> {
protected InputStreamSource convertResource(String resource) {
if (resource.startsWith("http://") || resource.startsWith("https://")) {
HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet(resource);
httpGet.setHeader(HttpHeaders.ACCEPT, "application/octet-stream");
Request request = new Request.Builder()
.url(resource)
.get()
.header("Accept", "application/octet-stream")
.build();
Call call = httpClient.newCall(request);
try {
HttpResponse response = httpClient.execute(httpGet);
InputStream inputStream = response.getEntity().getContent();
Response response = call.execute();
InputStream inputStream = Objects.requireNonNull(response.body()).byteStream();
new InputStreamResource(inputStream);
} catch (IOException e) {
e.printStackTrace();

View File

@ -34,8 +34,8 @@
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
</dependency>
</dependencies>

View File

@ -4,17 +4,11 @@ import com.alibaba.fastjson.JSONObject;
import com.simaek.notify.*;
import com.simaek.notify.sms.SmsProvider;
import com.simaek.notify.util.ExpressionUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import okhttp3.*;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
* 云信通短信通知平台通知器
@ -29,12 +23,12 @@ public class TelecomSmsNotifier implements Notifier<TelecomSmsTemplate> {
private final String notifierId;
private final CloseableHttpClient httpClient;
private final OkHttpClient httpClient;
public TelecomSmsNotifier(NotifierProperties properties) {
this.httpClient = HttpClientBuilder.create().build();
this.notifierId = properties.getId();
this.configuration = new JSONObject(properties.getConfiguration()).toJavaObject(TelecomSmsNotifierConfiguration.class);
this.httpClient = new OkHttpClient.Builder().build();
}
@Override
@ -55,21 +49,23 @@ public class TelecomSmsNotifier implements Notifier<TelecomSmsTemplate> {
@Override
public void send(TelecomSmsTemplate template, Map<String, Object> context) {
try {
URI sendMsgURI = new URIBuilder(notifyApi).addParameter("userId", configuration.getUserId())
.addParameter("password", configuration.getPassword())
.addParameter("content", render(template.getContent(), context))
.addParameter("mobile", template.getMobile())
HttpUrl url = Objects.requireNonNull(HttpUrl.parse(notifyApi)).newBuilder()
.addQueryParameter("userId", configuration.getUserId())
.addQueryParameter("password", configuration.getPassword())
.addQueryParameter("content", render(template.getContent(), context))
.addQueryParameter("mobile", template.getMobile())
.build();
HttpPost httpPost = new HttpPost(sendMsgURI);
CloseableHttpResponse response = httpClient.execute(httpPost);
String responseString = EntityUtils.toString(response.getEntity());
Map<String, String> resultMap = handleResponse(responseString);
Request request = new Request.Builder()
.url(url)
.post(RequestBody.create(new byte[0]))
.build();
Call call = httpClient.newCall(request);
Response response = call.execute();
Map<String, String> resultMap = handleResponse(Objects.requireNonNull(response.body()).string());
String resultCodeKey = "rspCode";
if (resultMap.containsKey(resultCodeKey)) {
if (!"0".equals(resultMap.get(resultCodeKey)) && !"DELIVRD".equalsIgnoreCase(resultMap.get(resultCodeKey))) {
if (!resultMap.containsKey(resultCodeKey) || (!"0".equals(resultMap.get(resultCodeKey)) && !"DELIVRD".equalsIgnoreCase(resultMap.get(resultCodeKey)))) {
throw new RuntimeException("短信发送失败:" + resultMap.get("rspDesc"));
}
}
} catch (Exception e) {
e.printStackTrace();
}
@ -77,11 +73,6 @@ public class TelecomSmsNotifier implements Notifier<TelecomSmsTemplate> {
@Override
public void close() {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**

View File

@ -45,7 +45,7 @@ public class TelecomSmsTest {
TelecomSmsTemplate template = new TelecomSmsTemplate();
template.setContent("${code}有效期为5分钟。");
template.setMobile("13047689449,18605120786");
template.setMobile("18605120786");
templateProperties.setTemplate(JSON.toJSONString(template));

View File

@ -29,8 +29,8 @@
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
</dependency>
</dependencies>

View File

@ -7,22 +7,12 @@ import com.simaek.notify.Notifier;
import com.simaek.notify.NotifyType;
import com.simaek.notify.Provider;
import com.simaek.notify.wechat.WechatProvider;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import okhttp3.*;
import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class WechatCorpNotifier implements Notifier<WechatCorpTemplate> {
@ -40,9 +30,12 @@ public class WechatCorpNotifier implements Notifier<WechatCorpTemplate> {
private final String notifierId;
private final OkHttpClient httpClient;
public WechatCorpNotifier(String id, WechatCorpProperties properties) {
this.properties = properties;
this.notifierId = id;
this.httpClient = new OkHttpClient.Builder().build();
}
@Override
@ -62,17 +55,18 @@ public class WechatCorpNotifier implements Notifier<WechatCorpTemplate> {
@Override
public void send(WechatCorpTemplate template, Map<String, Object> context) {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(notifyApi + "?access_token=" + getToken());
httpPost.setHeader("Content-Type", "application/json;charset=utf8");
StringEntity stringEntity = new StringEntity(template.createJsonRequest(context), "UTF-8");
httpPost.setEntity(stringEntity);
HttpUrl url = Objects.requireNonNull(HttpUrl.parse(notifyApi)).newBuilder()
.addQueryParameter("access_token", getToken())
.build();
Request request = new Request.Builder()
.url(url)
.post(RequestBody.create(template.createJsonRequest(context), MediaType.get("application/json")))
.header("Content-Type", "application/json;charset=utf8")
.build();
try {
CloseableHttpResponse response = httpClient.execute(httpPost);
String result = EntityUtils.toString(response.getEntity());
System.out.println(result);
Call call = httpClient.newCall(request);
Response response = call.execute();
String result = Objects.requireNonNull(response.body()).string();
JSONObject jsonObject = JSON.parseObject(result);
if (!"0".equals(jsonObject.get("errcode").toString())) {
throw new RuntimeException("发送微信企业通知失败:" + jsonObject.get("errmsg"));
@ -90,15 +84,18 @@ public class WechatCorpNotifier implements Notifier<WechatCorpTemplate> {
}
private String requestToken() {
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("corpId", properties.getCorpId()));
params.add(new BasicNameValuePair("corpSecret", properties.getCorpSecret()));
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpUrl url = Objects.requireNonNull(HttpUrl.parse(tokenApi)).newBuilder()
.addQueryParameter("corpId", properties.getCorpId())
.addQueryParameter("corpSecret", properties.getCorpSecret())
.build();
Request request = new Request.Builder()
.url(url)
.get()
.build();
try {
HttpGet httpGet = new HttpGet(new URIBuilder(tokenApi).setParameters(params).build());
CloseableHttpResponse response = httpClient.execute(httpGet);
JSONObject responseJson = JSON.parseObject(EntityUtils.toString(response.getEntity()));
Call call = httpClient.newCall(request);
Response response = call.execute();
JSONObject responseJson = JSON.parseObject(Objects.requireNonNull(response.body()).string());
if (responseJson.containsKey("access_token")) {
String access_token = responseJson.get("access_token").toString();
accessToken = access_token;

View File

@ -4,21 +4,12 @@ import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.simaek.notify.*;
import com.simaek.notify.wechat.WechatProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import okhttp3.*;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.Duration;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
/**
@ -59,11 +50,11 @@ public class WechatSubscriptionNotifier implements Notifier<WechatSubscriptionTe
*/
private long refreshTokenTime;
private final CloseableHttpClient httpClient;
private final OkHttpClient httpClient;
public WechatSubscriptionNotifier(NotifierProperties properties) {
this.properties = properties;
this.httpClient = HttpClientBuilder.create().build();
this.httpClient = new OkHttpClient.Builder().build();
}
@Override
@ -83,21 +74,23 @@ public class WechatSubscriptionNotifier implements Notifier<WechatSubscriptionTe
@Override
public void send(WechatSubscriptionTemplate template, Map<String, Object> context) {
try {
URI sendMessageURI = new URIBuilder(notifyApi)
.addParameter("access_token", getToken())
HttpUrl url = Objects.requireNonNull(HttpUrl.parse(notifyApi)).newBuilder()
.addQueryParameter("access_token", getToken())
.build();
HttpPost httpPost = new HttpPost(sendMessageURI);
httpPost.setHeader("Content-Type", "application/json; charset=UTF-8");
StringEntity requestBody = new StringEntity(template.createJsonRequest(), ContentType.APPLICATION_JSON);
httpPost.setEntity(requestBody);
CloseableHttpResponse response = httpClient.execute(httpPost);
JSONObject responseJson = JSON.parseObject(EntityUtils.toString(response.getEntity()));
Request request = new Request.Builder()
.url(url)
.header("Content-Type", "application/json; charset=UTF-8")
.post(RequestBody.create(template.createJsonRequest(), MediaType.get("application/json")))
.build();
try {
Call call = httpClient.newCall(request);
Response response = call.execute();
JSONObject responseJson = JSON.parseObject(Objects.requireNonNull(response.body()).string());
System.out.println(responseJson);
if (!responseJson.containsKey("errcode") || responseJson.getIntValue("errcode") != 0) {
throw new RuntimeException(responseJson.get("errmsg").toString());
}
} catch (URISyntaxException | IOException e) {
} catch (IOException e) {
e.printStackTrace();
}
}
@ -106,11 +99,6 @@ public class WechatSubscriptionNotifier implements Notifier<WechatSubscriptionTe
public void close() {
accessToken.set(null);
refreshTokenTime = 0;
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private String getToken() {
@ -125,22 +113,25 @@ public class WechatSubscriptionNotifier implements Notifier<WechatSubscriptionTe
*/
private void refreshToken() {
WechatSubscriptionProperties config = new JSONObject(properties.getConfiguration()).toJavaObject(WechatSubscriptionProperties.class);
try {
URI getTokenURI = new URIBuilder(tokenApi)
.addParameter("grant_type", config.getGrantType())
.addParameter("appid", config.getAppId())
.addParameter("secret", config.getSecret())
HttpUrl url = HttpUrl.parse(tokenApi).newBuilder()
.addQueryParameter("grant_type", config.getGrantType())
.addQueryParameter("appid", config.getAppId())
.addQueryParameter("secret", config.getSecret())
.build();
HttpGet httpGet = new HttpGet(getTokenURI);
CloseableHttpResponse response = httpClient.execute(httpGet);
String responseString = EntityUtils.toString(response.getEntity());
JSONObject responseJson = JSON.parseObject(responseString);
Request request = new Request.Builder()
.url(url)
.get()
.build();
try {
Call call = httpClient.newCall(request);
Response response = call.execute();
JSONObject responseJson = JSON.parseObject(Objects.requireNonNull(response.body()).string());
if (responseJson.containsKey("access_token")) {
accessToken.set(responseJson.get("access_token").toString());
} else if (responseJson.containsKey("errcode")) {
throw new RuntimeException(responseJson.get("errmsg").toString());
}
} catch (URISyntaxException | IOException e) {
} catch (IOException e) {
e.printStackTrace();
}
}

View File

@ -27,8 +27,8 @@ public class WechatTest {
notifierProperties.setId("12");
Map<String, Object> config = new HashMap<>();
config.put("corpId", "wwbd49ae2419a55a9f");
config.put("corpSecret", "TXDRQw_H8gpVKX0E01EmwMXJ4VooXmj65I-mDe0wQ1k");
config.put("corpId", "ww27a579a37932f608");
config.put("corpSecret", "V3e3ore5zuiZmZZ1qYweebr6N1MFo37uGN4xoDwtnu8");
notifierProperties.setConfiguration(config);
@ -44,8 +44,8 @@ public class WechatTest {
templateProperties.setProvider(WechatProvider.corpMessage.getId());
WechatCorpTemplate template = new WechatCorpTemplate();
template.setAgentId("3010084");
template.setToUser("XueYe");
template.setAgentId("1000002");
template.setToUser("Hsueh");
template.setToParty("");
template.setToTag("");
template.setMessage("Hello");