Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: HttpClient 线程安全, 可以全局复用, 也可配置自定义的 httpClient 到 WxClient. #85

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
*.ipr
*.iws
**/*.iml
**/*.DS_Store

.project
.classpath
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,11 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
Expand All @@ -34,24 +38,30 @@ public class WxClient {

private static Logger logger = LoggerFactory.getLogger(WxClient.class);

protected CloseableHttpClient httpClient;
protected static CloseableHttpClient httpClient;
private String clientId;
private String clientSecret;
private AccessTokenHolder accessTokenHolder;

public WxClient() {
httpClient = HttpClients.createDefault();
if (httpClient == null) {
httpClient = HttpClients.createDefault();
}
}

public WxClient(String tokenUrl, String clientId, String clientSecret) {
this(clientId, clientSecret, new DefaultAccessTokenHolder(tokenUrl, clientId, clientSecret));
}

public WxClient(String clientId, String clientSecret, AccessTokenHolder accessTokenHolder) {
this();
this.clientId = clientId;
this.clientSecret = clientSecret;
this.accessTokenHolder = accessTokenHolder;
httpClient = HttpClients.createDefault();
}

public static void setDefaultHttpClient(CloseableHttpClient httpClient) {
WxClient.httpClient = httpClient;
}

public String getClientId() {
Expand All @@ -75,13 +85,13 @@ public String get(String url) {
}

public String get(String url, boolean needToken) {
if(needToken) {
if (needToken) {
try {
return httpGet(appendAccessToken(url));
} catch (Exception e) {
if(e instanceof WxRuntimeException) {
if (e instanceof WxRuntimeException) {
WxRuntimeException wxRuntimeException = (WxRuntimeException) e;
if(invalidToken(wxRuntimeException.getCode())) {
if (invalidToken(wxRuntimeException.getCode())) {
logger.warn("token invalid: {}, will refresh.", wxRuntimeException.getCode());
refreshToken();
return httpGet(appendAccessToken(url));
Expand All @@ -95,13 +105,13 @@ public String get(String url, boolean needToken) {
}

public byte[] getBinary(String url, boolean needToken) {
if(needToken) {
if (needToken) {
try {
return httpGetBinary(appendAccessToken(url));
} catch (Exception e) {
if(e instanceof WxRuntimeException) {
if (e instanceof WxRuntimeException) {
WxRuntimeException wxRuntimeException = (WxRuntimeException) e;
if(invalidToken(wxRuntimeException.getCode())) {
if (invalidToken(wxRuntimeException.getCode())) {
logger.warn("token invalid: {}, will refresh.", wxRuntimeException.getCode());
refreshToken();
return httpGetBinary(appendAccessToken(url));
Expand Down Expand Up @@ -172,9 +182,9 @@ public File download(String url) {
try {
return httpDownload(appendAccessToken(url));
} catch (Exception e) {
if(e instanceof WxRuntimeException) {
if (e instanceof WxRuntimeException) {
WxRuntimeException wxRuntimeException = (WxRuntimeException) e;
if(invalidToken(wxRuntimeException.getCode())) {
if (invalidToken(wxRuntimeException.getCode())) {
logger.warn("token invalid: {}, will refresh.", wxRuntimeException.getCode());
refreshToken();
return httpDownload(appendAccessToken(url));
Expand All @@ -188,9 +198,9 @@ public InputStream copyStream(String url, String post) {
try {
return httpCopyFromStream(appendAccessToken(url), post);
} catch (Exception e) {
if(e instanceof WxRuntimeException) {
if (e instanceof WxRuntimeException) {
WxRuntimeException wxRuntimeException = (WxRuntimeException) e;
if(invalidToken(wxRuntimeException.getCode())) {
if (invalidToken(wxRuntimeException.getCode())) {
logger.warn("token invalid: {}, will refresh.", wxRuntimeException.getCode());
refreshToken();
return httpCopyFromStream(appendAccessToken(url), post);
Expand All @@ -202,9 +212,10 @@ public InputStream copyStream(String url, String post) {

/**
* 永久素材下载使用,奇葩的下载方式
* @param url
* @param post
* @return
*
* @param url request url
* @param post post content
* @return ByteArrayInputStream or Exception when error occured
*/
private InputStream httpCopyFromStream(String url, String post) {
HttpPost httpPost = new HttpPost(url);
Expand All @@ -223,7 +234,7 @@ private InputStream httpCopyFromStream(String url, String post) {
} else {
InputStream inputStream = entity.getContent();
byte[] binaryContent = IOUtils.toByteArray(inputStream);
String content = new String(binaryContent, "UTF-8");
String content = new String(binaryContent, StandardCharsets.UTF_8);
if (content.contains("errcode")) {
WxError wxError = WxError.fromJson(content);
throw new WxRuntimeException(wxError);
Expand Down Expand Up @@ -260,7 +271,7 @@ private File httpDownload(String url) {

return tempFile;
} else {
String errors = entity == null ? null : EntityUtils.toString(entity, Consts.UTF_8);
String errors = entity == null ? "" : EntityUtils.toString(entity, Consts.UTF_8);
logger.warn("download file : {} failed: {}", url, errors);
if (errors.contains("errcode")) {
WxError wxError = WxError.fromJson(errors);
Expand Down Expand Up @@ -292,9 +303,9 @@ public String post(String url, String content) {
try {
return httpPost(appendAccessToken(url), content);
} catch (Exception e) {
if(e instanceof WxRuntimeException) {
if (e instanceof WxRuntimeException) {
WxRuntimeException wxRuntimeException = (WxRuntimeException) e;
if(invalidToken(wxRuntimeException.getCode())) {
if (invalidToken(wxRuntimeException.getCode())) {
logger.warn("token invalid: {}, will refresh.", wxRuntimeException.getCode());
refreshToken();
return httpPost(appendAccessToken(url), content);
Expand All @@ -317,9 +328,9 @@ public String post(String url, InputStream inputStream, String fileName, Map<Str
try {
return httpPost(appendAccessToken(url), tempFile, form);
} catch (Exception e) {
if(e instanceof WxRuntimeException) {
if (e instanceof WxRuntimeException) {
WxRuntimeException wxRuntimeException = (WxRuntimeException) e;
if(invalidToken(wxRuntimeException.getCode())) {
if (invalidToken(wxRuntimeException.getCode())) {
logger.warn("token invalid: {}, will refresh.", wxRuntimeException.getCode());
refreshToken();
return httpPost(appendAccessToken(url), tempFile, form);
Expand Down Expand Up @@ -374,8 +385,8 @@ private String httpPost(String url, File file, Map<String, String> form) {
if (file != null) {
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.addBinaryBody("media", file).setMode(HttpMultipartMode.RFC6532);
if(form != null && !form.isEmpty()) {
for(String key: form.keySet()) {
if (form != null && !form.isEmpty()) {
for (String key : form.keySet()) {
multipartEntityBuilder.addTextBody(key, form.get(key));
}
}
Expand Down Expand Up @@ -413,7 +424,7 @@ public AccessToken getAccessToken() {

private boolean invalidToken(int code) {
boolean result = code == 42001 || code == 40001 || code == 40014;
if(result) {
if (result) {
accessTokenHolder.expireToken();//强制设置为无效
}
return result;
Expand Down