使用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> <dependency>
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId> <artifactId>spring-expression</artifactId>
<scope>provided</scope>
</dependency> </dependency>
</dependencies> </dependencies>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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