From 54639826dd638a40e2498d155a1c62ce66ed92d0 Mon Sep 17 00:00:00 2001 From: crskyp Date: Tue, 9 May 2017 10:29:57 +0800 Subject: [PATCH 01/13] =?UTF-8?q?RequestExecutor=E5=AE=9E=E4=BE=8B?= =?UTF-8?q?=E4=BF=AE=E6=94=B9=E4=B8=BA=E9=80=9A=E8=BF=87create=E6=96=B9?= =?UTF-8?q?=E6=B3=95=E6=9E=84=E5=BB=BA=EF=BC=8C=E8=A7=A3=E5=86=B3=E4=BA=86?= =?UTF-8?q?=E5=BF=85=E9=A1=BB=E5=90=8C=E6=97=B6=E5=BC=95=E5=85=A5apache-ht?= =?UTF-8?q?tp=E3=80=81jodd-http=E3=80=81okhttp=20jar=E7=9A=84=E9=97=AE?= =?UTF-8?q?=E9=A2=98=20=20=20(#223)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 5 + .../util/http/AbstractRequestExecutor.java | 46 ---- .../http/MediaDownloadRequestExecutor.java | 214 ++---------------- .../util/http/MediaUploadRequestExecutor.java | 124 ++-------- .../common/util/http/RequestExecutor.java | 14 +- .../util/http/SimpleGetRequestExecutor.java | 132 ++--------- .../util/http/SimplePostRequestExecutor.java | 150 ++---------- .../ApacheMediaDownloadRequestExecutor.java | 90 ++++++++ .../ApacheMediaUploadRequestExecutor.java | 58 +++++ .../ApacheSimpleGetRequestExecutor.java | 52 +++++ .../ApacheSimplePostRequestExecutor.java | 63 ++++++ .../JoddMediaDownloadRequestExecutor.java | 79 +++++++ .../jodd/JoddMediaUploadRequestExecutor.java | 41 ++++ .../jodd/JoddSimpleGetRequestExecutor.java | 54 +++++ .../jodd/JoddSimplePostRequestExecutor.java | 58 +++++ .../OkMediaDownloadRequestExecutor.java | 92 ++++++++ .../okhttp/OkMediaUploadRequestExecutor.java | 56 +++++ .../okhttp/OkSimpleGetRequestExecutor.java | 63 ++++++ .../okhttp/OkSimplePostRequestExecutor.java | 59 +++++ .../cp/api/impl/AbstractWxCpServiceImpl.java | 14 +- .../weixin/mp/api/WxMpCardService.java | 2 +- .../me/chanjar/weixin/mp/api/WxMpService.java | 7 + .../mp/api/impl/AbstractWxMpServiceImpl.java | 21 +- .../mp/api/impl/WxMpCardServiceImpl.java | 6 +- .../mp/api/impl/WxMpKefuServiceImpl.java | 2 +- .../mp/api/impl/WxMpMaterialServiceImpl.java | 16 +- .../mp/api/impl/WxMpQrcodeServiceImpl.java | 2 +- .../impl/WxMpUserBlacklistServiceImpl.java | 6 +- .../mp/api/impl/apache/WxMpServiceImpl.java | 5 + .../mp/api/impl/jodd/WxMpServiceImpl.java | 6 + .../mp/api/impl/okhttp/WxMpServiceImpl.java | 6 + .../http/MaterialDeleteRequestExecutor.java | 96 ++------ .../http/MaterialNewsInfoRequestExecutor.java | 98 ++------ .../http/MaterialUploadRequestExecutor.java | 137 ++--------- .../MaterialVideoInfoRequestExecutor.java | 97 ++------ ...lVoiceAndImageDownloadRequestExecutor.java | 129 ++--------- .../http/MediaImgUploadRequestExecutor.java | 112 ++------- .../mp/util/http/QrCodeRequestExecutor.java | 112 ++------- .../ApacheMaterialDeleteRequestExecutor.java | 52 +++++ ...ApacheMaterialNewsInfoRequestExecutor.java | 54 +++++ .../ApacheMaterialUploadRequestExecutor.java | 75 ++++++ ...pacheMaterialVideoInfoRequestExecutor.java | 53 +++++ ...lVoiceAndImageDownloadRequestExecutor.java | 64 ++++++ .../ApacheMediaImgUploadRequestExecutor.java | 61 +++++ .../apache/ApacheQrCodeRequestExecutor.java | 66 ++++++ .../JoddMaterialDeleteRequestExecutor.java | 40 ++++ .../JoddMaterialNewsInfoRequestExecutor.java | 43 ++++ .../JoddMaterialUploadRequestExecutor.java | 59 +++++ .../JoddMaterialVideoInfoRequestExecutor.java | 41 ++++ ...lVoiceAndImageDownloadRequestExecutor.java | 56 +++++ .../JoddMediaImgUploadRequestExecutor.java | 46 ++++ .../http/jodd/JoddQrCodeRequestExecutor.java | 57 +++++ .../OkhttpMaterialDeleteRequestExecutor.java | 54 +++++ ...OkhttpMaterialNewsInfoRequestExecutor.java | 55 +++++ .../OkhttpMaterialUploadRequestExecutor.java | 80 +++++++ ...khttpMaterialVideoInfoRequestExecutor.java | 52 +++++ ...lVoiceAndImageDownloadRequestExecutor.java | 68 ++++++ .../OkhttpMediaImgUploadRequestExecutor.java | 56 +++++ .../okhttp/OkhttpQrCodeRequestExecutor.java | 58 +++++ 59 files changed, 2219 insertions(+), 1295 deletions(-) delete mode 100644 weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/AbstractRequestExecutor.java create mode 100644 weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheMediaDownloadRequestExecutor.java create mode 100644 weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheMediaUploadRequestExecutor.java create mode 100644 weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheSimpleGetRequestExecutor.java create mode 100644 weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheSimplePostRequestExecutor.java create mode 100644 weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/jodd/JoddMediaDownloadRequestExecutor.java create mode 100644 weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/jodd/JoddMediaUploadRequestExecutor.java create mode 100644 weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/jodd/JoddSimpleGetRequestExecutor.java create mode 100644 weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/jodd/JoddSimplePostRequestExecutor.java create mode 100644 weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/okhttp/OkMediaDownloadRequestExecutor.java create mode 100644 weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/okhttp/OkMediaUploadRequestExecutor.java create mode 100644 weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/okhttp/OkSimpleGetRequestExecutor.java create mode 100644 weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/okhttp/OkSimplePostRequestExecutor.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialDeleteRequestExecutor.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialNewsInfoRequestExecutor.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialUploadRequestExecutor.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialVideoInfoRequestExecutor.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialVoiceAndImageDownloadRequestExecutor.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMediaImgUploadRequestExecutor.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheQrCodeRequestExecutor.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialDeleteRequestExecutor.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialNewsInfoRequestExecutor.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialUploadRequestExecutor.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialVideoInfoRequestExecutor.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialVoiceAndImageDownloadRequestExecutor.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMediaImgUploadRequestExecutor.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddQrCodeRequestExecutor.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialDeleteRequestExecutor.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialNewsInfoRequestExecutor.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialUploadRequestExecutor.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialVideoInfoRequestExecutor.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialVoiceAndImageDownloadRequestExecutor.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMediaImgUploadRequestExecutor.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpQrCodeRequestExecutor.java diff --git a/pom.xml b/pom.xml index 9a2fa9bd..dbe53d12 100644 --- a/pom.xml +++ b/pom.xml @@ -74,6 +74,11 @@ aimilin@yeah.net https://github.com/aimilin6688 + + ecoolper + crskyp@gmail.com + https://github.com/crskyp + diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/AbstractRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/AbstractRequestExecutor.java deleted file mode 100644 index 731bec77..00000000 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/AbstractRequestExecutor.java +++ /dev/null @@ -1,46 +0,0 @@ -package me.chanjar.weixin.common.util.http; - -import java.io.IOException; - -import org.apache.http.HttpHost; -import org.apache.http.impl.client.CloseableHttpClient; - -import jodd.http.HttpConnectionProvider; -import jodd.http.ProxyInfo; -import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.common.util.http.okhttp.OkhttpProxyInfo; -import okhttp3.ConnectionPool; - -/** - * Created by ecoolper on 2017/4/27. - */ -public abstract class AbstractRequestExecutor implements RequestExecutor { - - @Override - public T execute(RequestHttp requestHttp, String uri, E data) throws WxErrorException, IOException { - switch (requestHttp.getRequestType()) { - case apacheHttp: { - //apache-http请求 - CloseableHttpClient httpClient = (CloseableHttpClient) requestHttp.getRequestHttpClient(); - HttpHost httpProxy = (HttpHost) requestHttp.getRequestHttpProxy(); - return executeApache(httpClient, httpProxy, uri, data); - } - case joddHttp: { - //jodd-http请求 - HttpConnectionProvider provider = (HttpConnectionProvider) requestHttp.getRequestHttpClient(); - ProxyInfo proxyInfo = (ProxyInfo) requestHttp.getRequestHttpProxy(); - return executeJodd(provider, proxyInfo, uri, data); - } - case okHttp: { - //okhttp请求 - ConnectionPool pool = (ConnectionPool) requestHttp.getRequestHttpClient(); - OkhttpProxyInfo proxyInfo = (OkhttpProxyInfo) requestHttp.getRequestHttpProxy(); - return executeOkhttp(pool, proxyInfo, uri, data); - } - default: - //TODO 这里需要抛出异常,需要优化 - return null; - } - } - -} diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MediaDownloadRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MediaDownloadRequestExecutor.java index 6da7c65c..8ea7658d 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MediaDownloadRequestExecutor.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MediaDownloadRequestExecutor.java @@ -8,8 +8,11 @@ import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.bean.result.WxMediaUploadResult; import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.common.util.fs.FileUtils; +import me.chanjar.weixin.common.util.http.apache.ApacheMediaDownloadRequestExecutor; import me.chanjar.weixin.common.util.http.apache.InputStreamResponseHandler; import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; +import me.chanjar.weixin.common.util.http.jodd.JoddMediaDownloadRequestExecutor; +import me.chanjar.weixin.common.util.http.okhttp.OkMediaDownloadRequestExecutor; import me.chanjar.weixin.common.util.http.okhttp.OkhttpProxyInfo; import okhttp3.*; @@ -37,207 +40,26 @@ import java.util.regex.Pattern; * * @author Daniel Qian */ -public class MediaDownloadRequestExecutor extends AbstractRequestExecutor { - - private File tmpDirFile; - - public MediaDownloadRequestExecutor(File tmpDirFile) { - this.tmpDirFile = tmpDirFile; - } - - private String getFileName(HttpResponse response) throws WxErrorException { - String content = response.header("Content-disposition"); - if (content == null || content.length() == 0) { - throw new WxErrorException(WxError.newBuilder().setErrorMsg("无法获取到文件名").build()); - } - - Pattern p = Pattern.compile(".*filename=\"(.*)\""); - Matcher m = p.matcher(content); - if (m.matches()) { - return m.group(1); - } - throw new WxErrorException(WxError.newBuilder().setErrorMsg("无法获取到文件名").build()); - } - - private String getFileName(CloseableHttpResponse response) throws WxErrorException { - Header[] contentDispositionHeader = response.getHeaders("Content-disposition"); - if (contentDispositionHeader == null || contentDispositionHeader.length == 0) { - throw new WxErrorException(WxError.newBuilder().setErrorMsg("无法获取到文件名").build()); - } - - Pattern p = Pattern.compile(".*filename=\"(.*)\""); - Matcher m = p.matcher(contentDispositionHeader[0].getValue()); - if (m.matches()) { - return m.group(1); - } - throw new WxErrorException(WxError.newBuilder().setErrorMsg("无法获取到文件名").build()); - } - - - /** - * apache-http实现方式 - * - * @param httpclient - * @param httpProxy - * @param uri - * @param queryParam - * @return - * @throws WxErrorException - * @throws IOException - */ - public File executeApache(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String queryParam) throws WxErrorException, IOException { - if (queryParam != null) { - if (uri.indexOf('?') == -1) { - uri += '?'; - } - uri += uri.endsWith("?") ? queryParam : '&' + queryParam; - } - - HttpGet httpGet = new HttpGet(uri); - if (httpProxy != null) { - RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build(); - httpGet.setConfig(config); - } - - try (CloseableHttpResponse response = httpclient.execute(httpGet); - InputStream inputStream = InputStreamResponseHandler.INSTANCE - .handleResponse(response)) { - Header[] contentTypeHeader = response.getHeaders("Content-Type"); - if (contentTypeHeader != null && contentTypeHeader.length > 0) { - if (contentTypeHeader[0].getValue().startsWith(ContentType.APPLICATION_JSON.getMimeType())) { - // application/json; encoding=utf-8 下载媒体文件出错 - String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); - throw new WxErrorException(WxError.fromJson(responseContent)); - } - } - - String fileName = getFileName(response); - if (StringUtils.isBlank(fileName)) { +public abstract class MediaDownloadRequestExecutor implements RequestExecutor { + + public static RequestExecutor create(RequestHttp requestHttp, File tmpDirFile){ + switch (requestHttp.getRequestType()){ + case apacheHttp: + return new ApacheMediaDownloadRequestExecutor(requestHttp, tmpDirFile); + case joddHttp: + return new JoddMediaDownloadRequestExecutor(requestHttp, tmpDirFile); + case okHttp: + return new OkMediaDownloadRequestExecutor(requestHttp, tmpDirFile); + default: return null; - } - - String[] nameAndExt = fileName.split("\\."); - return FileUtils.createTmpFile(inputStream, nameAndExt[0], nameAndExt[1], this.tmpDirFile); - - } finally { - httpGet.releaseConnection(); } - } + protected RequestHttp requestHttp; + protected File tmpDirFile; - /** - * jodd-http实现方式 - * - * @param provider - * @param proxyInfo - * @param uri - * @param queryParam - * @return - * @throws WxErrorException - * @throws IOException - */ - public File executeJodd(HttpConnectionProvider provider, ProxyInfo proxyInfo, String uri, String queryParam) throws WxErrorException, IOException { - if (queryParam != null) { - if (uri.indexOf('?') == -1) { - uri += '?'; - } - uri += uri.endsWith("?") ? queryParam : '&' + queryParam; - } - - HttpRequest request = HttpRequest.get(uri); - if (proxyInfo != null) { - provider.useProxy(proxyInfo); - } - request.withConnectionProvider(provider); - - HttpResponse response = request.send(); - String contentType = response.header("Content-Type"); - if (contentType != null && contentType.startsWith("application/json")) { - // application/json; encoding=utf-8 下载媒体文件出错 - throw new WxErrorException(WxError.fromJson(response.bodyText())); - } - - String fileName = getFileName(response); - if (StringUtils.isBlank(fileName)) { - return null; - } - - InputStream inputStream = new ByteArrayInputStream(response.bodyBytes()); - String[] nameAndExt = fileName.split("\\."); - return FileUtils.createTmpFile(inputStream, nameAndExt[0], nameAndExt[1], this.tmpDirFile); - } - - - /** - * okhttp现实方式 - * - * @param pool - * @param proxyInfo - * @param uri - * @param queryParam - * @return - * @throws WxErrorException - * @throws IOException - */ - public File executeOkhttp(ConnectionPool pool, final OkhttpProxyInfo proxyInfo, String uri, String queryParam) throws WxErrorException, IOException { - if (queryParam != null) { - if (uri.indexOf('?') == -1) { - uri += '?'; - } - uri += uri.endsWith("?") ? queryParam : '&' + queryParam; - } - - OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder().connectionPool(pool); - //设置代理 - if (proxyInfo != null) { - clientBuilder.proxy(proxyInfo.getProxy()); - } - //设置授权 - clientBuilder.authenticator(new Authenticator() { - @Override - public Request authenticate(Route route, Response response) throws IOException { - String credential = Credentials.basic(proxyInfo.getProxyUsername(), proxyInfo.getProxyPassword()); - return response.request().newBuilder() - .header("Authorization", credential) - .build(); - } - }); - //得到httpClient - OkHttpClient client = clientBuilder.build(); - - Request request = new Request.Builder().url(uri).get().build(); - - Response response = client.newCall(request).execute(); - - String contentType = response.header("Content-Type"); - if (contentType != null && contentType.startsWith("application/json")) { - // application/json; encoding=utf-8 下载媒体文件出错 - throw new WxErrorException(WxError.fromJson(response.body().string())); - } - - String fileName = getFileName(response); - if (StringUtils.isBlank(fileName)) { - return null; - } - - InputStream inputStream = new ByteArrayInputStream(response.body().bytes()); - String[] nameAndExt = fileName.split("\\."); - return FileUtils.createTmpFile(inputStream, nameAndExt[0], nameAndExt[1], this.tmpDirFile); - } - - private String getFileName(Response response) throws WxErrorException { - String content = response.header("Content-disposition"); - if (content == null || content.length() == 0) { - throw new WxErrorException(WxError.newBuilder().setErrorMsg("无法获取到文件名").build()); - } - - Pattern p = Pattern.compile(".*filename=\"(.*)\""); - Matcher m = p.matcher(content); - if (m.matches()) { - return m.group(1); - } - throw new WxErrorException(WxError.newBuilder().setErrorMsg("无法获取到文件名").build()); + public MediaDownloadRequestExecutor(RequestHttp requestHttp, File tmpDirFile) { + this.tmpDirFile = tmpDirFile; } } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MediaUploadRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MediaUploadRequestExecutor.java index a6366f54..abe3dbd6 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MediaUploadRequestExecutor.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MediaUploadRequestExecutor.java @@ -7,8 +7,11 @@ import jodd.http.ProxyInfo; import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.bean.result.WxMediaUploadResult; import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.apache.ApacheMediaUploadRequestExecutor; import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; +import me.chanjar.weixin.common.util.http.jodd.JoddMediaUploadRequestExecutor; +import me.chanjar.weixin.common.util.http.okhttp.OkMediaUploadRequestExecutor; import me.chanjar.weixin.common.util.http.okhttp.OkhttpProxyInfo; import okhttp3.*; @@ -32,117 +35,24 @@ import java.net.Proxy; * * @author Daniel Qian */ -public class MediaUploadRequestExecutor extends AbstractRequestExecutor { +public abstract class MediaUploadRequestExecutor implements RequestExecutor { + protected RequestHttp requestHttp; - /** - * apache-http实现方式 - * - * @param httpclient - * @param httpProxy - * @param uri - * @param file - * @return - * @throws WxErrorException - * @throws IOException - */ - public WxMediaUploadResult executeApache(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, File file) throws WxErrorException, IOException { - HttpPost httpPost = new HttpPost(uri); - if (httpProxy != null) { - RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build(); - httpPost.setConfig(config); - } - if (file != null) { - HttpEntity entity = MultipartEntityBuilder - .create() - .addBinaryBody("media", file) - .setMode(HttpMultipartMode.RFC6532) - .build(); - httpPost.setEntity(entity); - httpPost.setHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString()); - } - try (CloseableHttpResponse response = httpclient.execute(httpPost)) { - String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); - WxError error = WxError.fromJson(responseContent); - if (error.getErrorCode() != 0) { - throw new WxErrorException(error); - } - return WxMediaUploadResult.fromJson(responseContent); - } finally { - httpPost.releaseConnection(); - } + public MediaUploadRequestExecutor(RequestHttp requestHttp){ + this.requestHttp =requestHttp; } - - /** - * jodd-http实现方式 - * - * @param provider - * @param proxyInfo - * @param uri - * @param file - * @return - * @throws WxErrorException - * @throws IOException - */ - public WxMediaUploadResult executeJodd(HttpConnectionProvider provider, ProxyInfo proxyInfo, String uri, File file) throws WxErrorException, IOException { - HttpRequest request = HttpRequest.post(uri); - if (proxyInfo != null) { - provider.useProxy(proxyInfo); + public static RequestExecutor create(RequestHttp requestHttp){ + switch (requestHttp.getRequestType()){ + case apacheHttp: + return new ApacheMediaUploadRequestExecutor(requestHttp); + case joddHttp: + return new JoddMediaUploadRequestExecutor(requestHttp); + case okHttp: + return new OkMediaUploadRequestExecutor(requestHttp); + default: + return null; } - request.withConnectionProvider(provider); - request.form("media", file); - HttpResponse response = request.send(); - String responseContent = response.bodyText(); - WxError error = WxError.fromJson(responseContent); - if (error.getErrorCode() != 0) { - throw new WxErrorException(error); - } - return WxMediaUploadResult.fromJson(responseContent); } - - /** - * okhttp现实方式 - * - * @param pool - * @param proxyInfo - * @param uri - * @param file - * @return - * @throws WxErrorException - * @throws IOException - */ - public WxMediaUploadResult executeOkhttp(ConnectionPool pool, final OkhttpProxyInfo proxyInfo, String uri, File file) throws WxErrorException, IOException { - OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder().connectionPool(pool); - //设置代理 - if (proxyInfo != null) { - clientBuilder.proxy(proxyInfo.getProxy()); - } - //设置授权 - clientBuilder.authenticator(new Authenticator() { - @Override - public Request authenticate(Route route, Response response) throws IOException { - String credential = Credentials.basic(proxyInfo.getProxyUsername(), proxyInfo.getProxyPassword()); - return response.request().newBuilder() - .header("Authorization", credential) - .build(); - } - }); - //得到httpClient - OkHttpClient client = clientBuilder.build(); - - RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), file); - RequestBody body = new MultipartBody.Builder().addFormDataPart("media", null, fileBody).build(); - Request request = new Request.Builder().url(uri).post(body).build(); - - Response response = client.newCall(request).execute(); - String responseContent = response.body().string(); - WxError error = WxError.fromJson(responseContent); - if (error.getErrorCode() != 0) { - throw new WxErrorException(error); - } - return WxMediaUploadResult.fromJson(responseContent); - } - - } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/RequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/RequestExecutor.java index 42fa76f9..b58249e9 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/RequestExecutor.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/RequestExecutor.java @@ -26,7 +26,7 @@ public interface RequestExecutor { * @throws WxErrorException * @throws IOException */ - T execute(RequestHttp requestHttp, String uri, E data) throws WxErrorException, IOException; + T execute(String uri, E data) throws WxErrorException, IOException; /** * apache-http实现方式 @@ -37,10 +37,10 @@ public interface RequestExecutor { * @return * @throws WxErrorException * @throws IOException - */ + *//* T executeApache(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, E data) throws WxErrorException, IOException; - /** + *//** * jodd-http实现方式 * @param provider * @param proxyInfo @@ -49,11 +49,11 @@ public interface RequestExecutor { * @return * @throws WxErrorException * @throws IOException - */ + *//* T executeJodd(HttpConnectionProvider provider, ProxyInfo proxyInfo, String uri, E data) throws WxErrorException, IOException; - /** okhttp实现方式 + *//** okhttp实现方式 * @param pool * @param proxyInfo * @param uri @@ -61,7 +61,7 @@ public interface RequestExecutor { * @return * @throws WxErrorException * @throws IOException - */ + *//* T executeOkhttp(ConnectionPool pool, final OkhttpProxyInfo proxyInfo, String uri, E data) throws WxErrorException, IOException; - +*/ } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimpleGetRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimpleGetRequestExecutor.java index f29739d6..ec7a2e57 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimpleGetRequestExecutor.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimpleGetRequestExecutor.java @@ -6,8 +6,11 @@ import jodd.http.HttpResponse; import jodd.http.ProxyInfo; import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.apache.ApacheSimpleGetRequestExecutor; import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; +import me.chanjar.weixin.common.util.http.jodd.JoddSimpleGetRequestExecutor; +import me.chanjar.weixin.common.util.http.okhttp.OkSimpleGetRequestExecutor; import me.chanjar.weixin.common.util.http.okhttp.OkhttpProxyInfo; import okhttp3.*; @@ -27,126 +30,25 @@ import java.util.concurrent.TimeUnit; * * @author Daniel Qian */ -public class SimpleGetRequestExecutor extends AbstractRequestExecutor { +public abstract class SimpleGetRequestExecutor implements RequestExecutor { + protected RequestHttp requestHttp; - - /** - * apache-http实现方式 - * - * @param httpclient - * @param httpProxy - * @param uri - * @param queryParam - * @return - * @throws WxErrorException - * @throws IOException - */ - public String executeApache(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String queryParam) throws WxErrorException, IOException { - if (queryParam != null) { - if (uri.indexOf('?') == -1) { - uri += '?'; - } - uri += uri.endsWith("?") ? queryParam : '&' + queryParam; - } - HttpGet httpGet = new HttpGet(uri); - if (httpProxy != null) { - RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build(); - httpGet.setConfig(config); - } - - try (CloseableHttpResponse response = httpclient.execute(httpGet)) { - String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); - WxError error = WxError.fromJson(responseContent); - if (error.getErrorCode() != 0) { - throw new WxErrorException(error); - } - return responseContent; - } finally { - httpGet.releaseConnection(); - } + public SimpleGetRequestExecutor(RequestHttp requestHttp){ + this.requestHttp =requestHttp; } - /** - * jodd-http实现方式 - * - * @param provider - * @param proxyInfo - * @param uri - * @param queryParam - * @return - * @throws WxErrorException - * @throws IOException - */ - public String executeJodd(HttpConnectionProvider provider, ProxyInfo proxyInfo, String uri, String queryParam) throws WxErrorException, IOException { - if (queryParam != null) { - if (uri.indexOf('?') == -1) { - uri += '?'; - } - uri += uri.endsWith("?") ? queryParam : '&' + queryParam; - } - - HttpRequest request = HttpRequest.get(uri); - if (proxyInfo != null) { - provider.useProxy(proxyInfo); - } - request.withConnectionProvider(provider); - HttpResponse response = request.send(); - String responseContent = response.bodyText(); - WxError error = WxError.fromJson(responseContent); - if (error.getErrorCode() != 0) { - throw new WxErrorException(error); - } - return responseContent; - } - - - /** - * okHttp实现方式 - * - * @param pool - * @param proxyInfo - * @param uri - * @param queryParam - * @return - * @throws WxErrorException - * @throws IOException - */ - public String executeOkhttp(ConnectionPool pool, final OkhttpProxyInfo proxyInfo, String uri, String queryParam) throws WxErrorException, IOException { - if (queryParam != null) { - if (uri.indexOf('?') == -1) { - uri += '?'; - } - uri += uri.endsWith("?") ? queryParam : '&' + queryParam; - } - - OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder().connectionPool(pool); - //设置代理 - if (proxyInfo != null) { - clientBuilder.proxy(proxyInfo.getProxy()); - } - //设置授权 - clientBuilder.authenticator(new Authenticator() { - @Override - public Request authenticate(Route route, Response response) throws IOException { - String credential = Credentials.basic(proxyInfo.getProxyUsername(), proxyInfo.getProxyPassword()); - return response.request().newBuilder() - .header("Authorization", credential) - .build(); - } - }); - //得到httpClient - OkHttpClient client =clientBuilder.build(); - - Request request = new Request.Builder().url(uri).build(); - - Response response = client.newCall(request).execute(); - String responseContent = response.body().string(); - WxError error = WxError.fromJson(responseContent); - if (error.getErrorCode() != 0) { - throw new WxErrorException(error); + public static RequestExecutor create(RequestHttp requestHttp){ + switch(requestHttp.getRequestType()){ + case apacheHttp: + return new ApacheSimpleGetRequestExecutor(requestHttp); + case joddHttp: + return new JoddSimpleGetRequestExecutor(requestHttp); + case okHttp: + return new OkSimpleGetRequestExecutor(requestHttp); + default: + return null; } - return responseContent; } } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimplePostRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimplePostRequestExecutor.java index c89309b7..c6f4e6a7 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimplePostRequestExecutor.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimplePostRequestExecutor.java @@ -6,8 +6,12 @@ import jodd.http.HttpResponse; import jodd.http.ProxyInfo; import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.apache.ApacheSimpleGetRequestExecutor; +import me.chanjar.weixin.common.util.http.apache.ApacheSimplePostRequestExecutor; import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; +import me.chanjar.weixin.common.util.http.jodd.JoddSimplePostRequestExecutor; +import me.chanjar.weixin.common.util.http.okhttp.OkSimplePostRequestExecutor; import me.chanjar.weixin.common.util.http.okhttp.OkhttpProxyInfo; import okhttp3.*; @@ -27,142 +31,24 @@ import java.io.IOException; * * @author Daniel Qian */ -public class SimplePostRequestExecutor extends AbstractRequestExecutor { +public abstract class SimplePostRequestExecutor implements RequestExecutor { + protected RequestHttp requestHttp; - /** - * apache-http实现方式 - * - * @param httpclient - * @param httpProxy - * @param uri - * @param postEntity - * @return - * @throws WxErrorException - * @throws IOException - */ - public String executeApache(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String postEntity) throws WxErrorException, IOException { - - HttpPost httpPost = new HttpPost(uri); - if (httpProxy != null) { - RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build(); - httpPost.setConfig(config); - } - - if (postEntity != null) { - StringEntity entity = new StringEntity(postEntity, Consts.UTF_8); - httpPost.setEntity(entity); - } - - try (CloseableHttpResponse response = httpclient.execute(httpPost)) { - String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); - if (responseContent.isEmpty()) { - throw new WxErrorException( - WxError.newBuilder().setErrorCode(9999).setErrorMsg("无响应内容") - .build()); - } - - if (responseContent.startsWith("")) { - //xml格式输出直接返回 - return responseContent; - } - - WxError error = WxError.fromJson(responseContent); - if (error.getErrorCode() != 0) { - throw new WxErrorException(error); - } - return responseContent; - } finally { - httpPost.releaseConnection(); - } - } - - - /** - * jodd-http实现方式 - * - * @param provider - * @param proxyInfo - * @param uri - * @param postEntity - * @return - * @throws WxErrorException - * @throws IOException - */ - public String executeJodd(HttpConnectionProvider provider, ProxyInfo proxyInfo, String uri, String postEntity) throws WxErrorException, IOException { - HttpRequest request = HttpRequest.post(uri); - if (proxyInfo != null) { - provider.useProxy(proxyInfo); - } - request.withConnectionProvider(provider); - if (postEntity != null) { - request.bodyText(postEntity); - } - HttpResponse response = request.send(); - - String responseContent = response.bodyText(); - if (responseContent.isEmpty()) { - throw new WxErrorException( - WxError.newBuilder().setErrorCode(9999).setErrorMsg("无响应内容") - .build()); - } - - if (responseContent.startsWith("")) { - //xml格式输出直接返回 - return responseContent; - } - - WxError error = WxError.fromJson(responseContent); - if (error.getErrorCode() != 0) { - throw new WxErrorException(error); - } - return responseContent; + public SimplePostRequestExecutor(RequestHttp requestHttp){ + this.requestHttp =requestHttp; } - - /** - * okHttp实现方式 - * - * @param pool - * @param proxyInfo - * @param uri - * @param postEntity - * @return - * @throws WxErrorException - * @throws IOException - */ - public String executeOkhttp(ConnectionPool pool, final OkhttpProxyInfo proxyInfo, String uri, String postEntity) throws WxErrorException, IOException { - OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder().connectionPool(pool); - //设置代理 - if (proxyInfo != null) { - clientBuilder.proxy(proxyInfo.getProxy()); + public static RequestExecutor create(RequestHttp requestHttp){ + switch (requestHttp.getRequestType()){ + case apacheHttp: + return new ApacheSimplePostRequestExecutor(requestHttp); + case joddHttp: + return new JoddSimplePostRequestExecutor(requestHttp); + case okHttp: + return new OkSimplePostRequestExecutor(requestHttp); + default: + return null; } - //设置授权 - clientBuilder.authenticator(new Authenticator() { - @Override - public Request authenticate(Route route, Response response) throws IOException { - String credential = Credentials.basic(proxyInfo.getProxyUsername(), proxyInfo.getProxyPassword()); - return response.request().newBuilder() - .header("Authorization", credential) - .build(); - } - }); - //得到httpClient - OkHttpClient client = clientBuilder.build(); - - - MediaType mediaType = MediaType.parse("text/plain; charset=utf-8"); - RequestBody body = RequestBody.create(mediaType, postEntity); - - Request request = new Request.Builder().url(uri).post(body).build(); - - Response response = client.newCall(request).execute(); - String responseContent = response.body().string(); - WxError error = WxError.fromJson(responseContent); - if (error.getErrorCode() != 0) { - throw new WxErrorException(error); - } - return responseContent; } - } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheMediaDownloadRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheMediaDownloadRequestExecutor.java new file mode 100644 index 00000000..8546a791 --- /dev/null +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheMediaDownloadRequestExecutor.java @@ -0,0 +1,90 @@ +package me.chanjar.weixin.common.util.http.apache; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.lang3.StringUtils; +import org.apache.http.Header; +import org.apache.http.HttpHost; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.entity.ContentType; +import org.apache.http.impl.client.CloseableHttpClient; + +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.bean.result.WxMediaUploadResult; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.fs.FileUtils; +import me.chanjar.weixin.common.util.http.MediaDownloadRequestExecutor; +import me.chanjar.weixin.common.util.http.RequestExecutor; +import me.chanjar.weixin.common.util.http.RequestHttp; + +/** + * Created by ecoolper on 2017/5/5. + */ +public class ApacheMediaDownloadRequestExecutor extends MediaDownloadRequestExecutor { + + + public ApacheMediaDownloadRequestExecutor(RequestHttp requestHttp, File tmpDirFile) { + super(requestHttp, tmpDirFile); + } + + @Override + public File execute(String uri, String queryParam) throws WxErrorException, IOException { + if (queryParam != null) { + if (uri.indexOf('?') == -1) { + uri += '?'; + } + uri += uri.endsWith("?") ? queryParam : '&' + queryParam; + } + + HttpGet httpGet = new HttpGet(uri); + if (requestHttp.getRequestHttpProxy() != null) { + RequestConfig config = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).build(); + httpGet.setConfig(config); + } + + try (CloseableHttpResponse response = requestHttp.getRequestHttpClient().execute(httpGet); + InputStream inputStream = InputStreamResponseHandler.INSTANCE + .handleResponse(response)) { + Header[] contentTypeHeader = response.getHeaders("Content-Type"); + if (contentTypeHeader != null && contentTypeHeader.length > 0) { + if (contentTypeHeader[0].getValue().startsWith(ContentType.APPLICATION_JSON.getMimeType())) { + // application/json; encoding=utf-8 下载媒体文件出错 + String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); + throw new WxErrorException(WxError.fromJson(responseContent)); + } + } + + String fileName = getFileName(response); + if (StringUtils.isBlank(fileName)) { + return null; + } + + String[] nameAndExt = fileName.split("\\."); + return FileUtils.createTmpFile(inputStream, nameAndExt[0], nameAndExt[1], super.tmpDirFile); + + } finally { + httpGet.releaseConnection(); + } + } + + private String getFileName(CloseableHttpResponse response) throws WxErrorException { + Header[] contentDispositionHeader = response.getHeaders("Content-disposition"); + if (contentDispositionHeader == null || contentDispositionHeader.length == 0) { + throw new WxErrorException(WxError.newBuilder().setErrorMsg("无法获取到文件名").build()); + } + + Pattern p = Pattern.compile(".*filename=\"(.*)\""); + Matcher m = p.matcher(contentDispositionHeader[0].getValue()); + if (m.matches()) { + return m.group(1); + } + throw new WxErrorException(WxError.newBuilder().setErrorMsg("无法获取到文件名").build()); + } + +} diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheMediaUploadRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheMediaUploadRequestExecutor.java new file mode 100644 index 00000000..a9c10a58 --- /dev/null +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheMediaUploadRequestExecutor.java @@ -0,0 +1,58 @@ +package me.chanjar.weixin.common.util.http.apache; + +import java.io.File; +import java.io.IOException; + +import org.apache.http.HttpEntity; +import org.apache.http.HttpHost; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.mime.HttpMultipartMode; +import org.apache.http.entity.mime.MultipartEntityBuilder; +import org.apache.http.impl.client.CloseableHttpClient; + +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.bean.result.WxMediaUploadResult; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.MediaUploadRequestExecutor; +import me.chanjar.weixin.common.util.http.RequestExecutor; +import me.chanjar.weixin.common.util.http.RequestHttp; + +/** + * Created by ecoolper on 2017/5/5. + */ +public class ApacheMediaUploadRequestExecutor extends MediaUploadRequestExecutor { + public ApacheMediaUploadRequestExecutor(RequestHttp requestHttp) { + super(requestHttp); + } + + @Override + public WxMediaUploadResult execute(String uri, File file) throws WxErrorException, IOException { + HttpPost httpPost = new HttpPost(uri); + if (requestHttp.getRequestHttpProxy() != null) { + RequestConfig config = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).build(); + httpPost.setConfig(config); + } + if (file != null) { + HttpEntity entity = MultipartEntityBuilder + .create() + .addBinaryBody("media", file) + .setMode(HttpMultipartMode.RFC6532) + .build(); + httpPost.setEntity(entity); + httpPost.setHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString()); + } + try (CloseableHttpResponse response = requestHttp.getRequestHttpClient().execute(httpPost)) { + String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); + WxError error = WxError.fromJson(responseContent); + if (error.getErrorCode() != 0) { + throw new WxErrorException(error); + } + return WxMediaUploadResult.fromJson(responseContent); + } finally { + httpPost.releaseConnection(); + } + } +} diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheSimpleGetRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheSimpleGetRequestExecutor.java new file mode 100644 index 00000000..9564fd36 --- /dev/null +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheSimpleGetRequestExecutor.java @@ -0,0 +1,52 @@ +package me.chanjar.weixin.common.util.http.apache; + +import java.io.IOException; + +import org.apache.http.HttpHost; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.CloseableHttpClient; + +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.RequestExecutor; +import me.chanjar.weixin.common.util.http.RequestHttp; +import me.chanjar.weixin.common.util.http.SimpleGetRequestExecutor; + +/** + * Created by ecoolper on 2017/5/4. + */ +public class ApacheSimpleGetRequestExecutor extends SimpleGetRequestExecutor { + + public ApacheSimpleGetRequestExecutor(RequestHttp requestHttp) { + super(requestHttp); + } + + @Override + public String execute(String uri, String queryParam) throws WxErrorException, IOException { + if (queryParam != null) { + if (uri.indexOf('?') == -1) { + uri += '?'; + } + uri += uri.endsWith("?") ? queryParam : '&' + queryParam; + } + HttpGet httpGet = new HttpGet(uri); + if (requestHttp.getRequestHttpProxy() != null) { + RequestConfig config = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).build(); + httpGet.setConfig(config); + } + + try (CloseableHttpResponse response = requestHttp.getRequestHttpClient().execute(httpGet)) { + String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); + WxError error = WxError.fromJson(responseContent); + if (error.getErrorCode() != 0) { + throw new WxErrorException(error); + } + return responseContent; + } finally { + httpGet.releaseConnection(); + } + } + +} diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheSimplePostRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheSimplePostRequestExecutor.java new file mode 100644 index 00000000..4e092c43 --- /dev/null +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheSimplePostRequestExecutor.java @@ -0,0 +1,63 @@ +package me.chanjar.weixin.common.util.http.apache; + +import java.io.IOException; + +import org.apache.http.Consts; +import org.apache.http.HttpHost; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; + +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.RequestExecutor; +import me.chanjar.weixin.common.util.http.RequestHttp; +import me.chanjar.weixin.common.util.http.SimplePostRequestExecutor; + +/** + * Created by ecoolper on 2017/5/4. + */ +public class ApacheSimplePostRequestExecutor extends SimplePostRequestExecutor { + + public ApacheSimplePostRequestExecutor(RequestHttp requestHttp) { + super(requestHttp); + } + + @Override + public String execute(String uri, String postEntity) throws WxErrorException, IOException { + HttpPost httpPost = new HttpPost(uri); + if (requestHttp.getRequestHttpProxy() != null) { + RequestConfig config = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).build(); + httpPost.setConfig(config); + } + + if (postEntity != null) { + StringEntity entity = new StringEntity(postEntity, Consts.UTF_8); + httpPost.setEntity(entity); + } + + try (CloseableHttpResponse response = requestHttp.getRequestHttpClient().execute(httpPost)) { + String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); + if (responseContent.isEmpty()) { + throw new WxErrorException( + WxError.newBuilder().setErrorCode(9999).setErrorMsg("无响应内容") + .build()); + } + + if (responseContent.startsWith("")) { + //xml格式输出直接返回 + return responseContent; + } + + WxError error = WxError.fromJson(responseContent); + if (error.getErrorCode() != 0) { + throw new WxErrorException(error); + } + return responseContent; + } finally { + httpPost.releaseConnection(); + } + } +} diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/jodd/JoddMediaDownloadRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/jodd/JoddMediaDownloadRequestExecutor.java new file mode 100644 index 00000000..f392f5ac --- /dev/null +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/jodd/JoddMediaDownloadRequestExecutor.java @@ -0,0 +1,79 @@ +package me.chanjar.weixin.common.util.http.jodd; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.lang3.StringUtils; + +import jodd.http.HttpConnectionProvider; +import jodd.http.HttpRequest; +import jodd.http.HttpResponse; +import jodd.http.ProxyInfo; +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.fs.FileUtils; +import me.chanjar.weixin.common.util.http.MediaDownloadRequestExecutor; +import me.chanjar.weixin.common.util.http.RequestExecutor; +import me.chanjar.weixin.common.util.http.RequestHttp; + +/** + * Created by ecoolper on 2017/5/5. + */ +public class JoddMediaDownloadRequestExecutor extends MediaDownloadRequestExecutor { + + + public JoddMediaDownloadRequestExecutor(RequestHttp requestHttp, File tmpDirFile) { + super(requestHttp, tmpDirFile); + } + + @Override + public File execute(String uri, String queryParam) throws WxErrorException, IOException { + if (queryParam != null) { + if (uri.indexOf('?') == -1) { + uri += '?'; + } + uri += uri.endsWith("?") ? queryParam : '&' + queryParam; + } + + HttpRequest request = HttpRequest.get(uri); + if (requestHttp.getRequestHttpProxy() != null) { + requestHttp.getRequestHttpClient().useProxy(requestHttp.getRequestHttpProxy()); + } + request.withConnectionProvider(requestHttp.getRequestHttpClient()); + + HttpResponse response = request.send(); + String contentType = response.header("Content-Type"); + if (contentType != null && contentType.startsWith("application/json")) { + // application/json; encoding=utf-8 下载媒体文件出错 + throw new WxErrorException(WxError.fromJson(response.bodyText())); + } + + String fileName = getFileName(response); + if (StringUtils.isBlank(fileName)) { + return null; + } + + InputStream inputStream = new ByteArrayInputStream(response.bodyBytes()); + String[] nameAndExt = fileName.split("\\."); + return FileUtils.createTmpFile(inputStream, nameAndExt[0], nameAndExt[1], super.tmpDirFile); + } + + private String getFileName(HttpResponse response) throws WxErrorException { + String content = response.header("Content-disposition"); + if (content == null || content.length() == 0) { + throw new WxErrorException(WxError.newBuilder().setErrorMsg("无法获取到文件名").build()); + } + + Pattern p = Pattern.compile(".*filename=\"(.*)\""); + Matcher m = p.matcher(content); + if (m.matches()) { + return m.group(1); + } + throw new WxErrorException(WxError.newBuilder().setErrorMsg("无法获取到文件名").build()); + } + +} diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/jodd/JoddMediaUploadRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/jodd/JoddMediaUploadRequestExecutor.java new file mode 100644 index 00000000..91cae4fc --- /dev/null +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/jodd/JoddMediaUploadRequestExecutor.java @@ -0,0 +1,41 @@ +package me.chanjar.weixin.common.util.http.jodd; + +import java.io.File; +import java.io.IOException; + +import jodd.http.HttpConnectionProvider; +import jodd.http.HttpRequest; +import jodd.http.HttpResponse; +import jodd.http.ProxyInfo; +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.bean.result.WxMediaUploadResult; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.MediaUploadRequestExecutor; +import me.chanjar.weixin.common.util.http.RequestExecutor; +import me.chanjar.weixin.common.util.http.RequestHttp; + +/** + * Created by ecoolper on 2017/5/5. + */ +public class JoddMediaUploadRequestExecutor extends MediaUploadRequestExecutor { + public JoddMediaUploadRequestExecutor(RequestHttp requestHttp) { + super(requestHttp); + } + + @Override + public WxMediaUploadResult execute(String uri, File file) throws WxErrorException, IOException { + HttpRequest request = HttpRequest.post(uri); + if (requestHttp.getRequestHttpProxy() != null) { + requestHttp.getRequestHttpClient().useProxy(requestHttp.getRequestHttpProxy()); + } + request.withConnectionProvider(requestHttp.getRequestHttpClient()); + request.form("media", file); + HttpResponse response = request.send(); + String responseContent = response.bodyText(); + WxError error = WxError.fromJson(responseContent); + if (error.getErrorCode() != 0) { + throw new WxErrorException(error); + } + return WxMediaUploadResult.fromJson(responseContent); + } +} diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/jodd/JoddSimpleGetRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/jodd/JoddSimpleGetRequestExecutor.java new file mode 100644 index 00000000..ea44e5a6 --- /dev/null +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/jodd/JoddSimpleGetRequestExecutor.java @@ -0,0 +1,54 @@ +package me.chanjar.weixin.common.util.http.jodd; + +import java.io.IOException; + +import org.apache.http.HttpHost; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.CloseableHttpClient; + +import jodd.http.HttpConnectionProvider; +import jodd.http.HttpRequest; +import jodd.http.HttpResponse; +import jodd.http.ProxyInfo; +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.RequestExecutor; +import me.chanjar.weixin.common.util.http.RequestHttp; +import me.chanjar.weixin.common.util.http.SimpleGetRequestExecutor; +import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; + +/** + * Created by ecoolper on 2017/5/4. + */ +public class JoddSimpleGetRequestExecutor extends SimpleGetRequestExecutor { + + public JoddSimpleGetRequestExecutor(RequestHttp requestHttp) { + super(requestHttp); + } + + @Override + public String execute(String uri, String queryParam) throws WxErrorException, IOException { + if (queryParam != null) { + if (uri.indexOf('?') == -1) { + uri += '?'; + } + uri += uri.endsWith("?") ? queryParam : '&' + queryParam; + } + + HttpRequest request = HttpRequest.get(uri); + if (requestHttp.getRequestHttpProxy() != null) { + requestHttp.getRequestHttpClient().useProxy(requestHttp.getRequestHttpProxy()); + } + request.withConnectionProvider(requestHttp.getRequestHttpClient()); + HttpResponse response = request.send(); + String responseContent = response.bodyText(); + WxError error = WxError.fromJson(responseContent); + if (error.getErrorCode() != 0) { + throw new WxErrorException(error); + } + return responseContent; + } + +} diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/jodd/JoddSimplePostRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/jodd/JoddSimplePostRequestExecutor.java new file mode 100644 index 00000000..59eea7b2 --- /dev/null +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/jodd/JoddSimplePostRequestExecutor.java @@ -0,0 +1,58 @@ +package me.chanjar.weixin.common.util.http.jodd; + +import java.io.IOException; + +import jodd.http.HttpConnectionProvider; +import jodd.http.HttpRequest; +import jodd.http.HttpResponse; +import jodd.http.ProxyInfo; +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.RequestExecutor; +import me.chanjar.weixin.common.util.http.RequestHttp; +import me.chanjar.weixin.common.util.http.SimplePostRequestExecutor; + +/** + * Created by ecoolper on 2017/5/4. + */ +public class JoddSimplePostRequestExecutor extends SimplePostRequestExecutor { + + public JoddSimplePostRequestExecutor(RequestHttp requestHttp) { + super(requestHttp); + } + + @Override + public String execute(String uri, String postEntity) throws WxErrorException, IOException { + HttpConnectionProvider provider = requestHttp.getRequestHttpClient(); + ProxyInfo proxyInfo = requestHttp.getRequestHttpProxy(); + + HttpRequest request = HttpRequest.post(uri); + if (proxyInfo != null) { + provider.useProxy(proxyInfo); + } + request.withConnectionProvider(provider); + if (postEntity != null) { + request.bodyText(postEntity); + } + HttpResponse response = request.send(); + + String responseContent = response.bodyText(); + if (responseContent.isEmpty()) { + throw new WxErrorException( + WxError.newBuilder().setErrorCode(9999).setErrorMsg("无响应内容") + .build()); + } + + if (responseContent.startsWith("")) { + //xml格式输出直接返回 + return responseContent; + } + + WxError error = WxError.fromJson(responseContent); + if (error.getErrorCode() != 0) { + throw new WxErrorException(error); + } + return responseContent; + } + +} diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/okhttp/OkMediaDownloadRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/okhttp/OkMediaDownloadRequestExecutor.java new file mode 100644 index 00000000..a2f6f8ed --- /dev/null +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/okhttp/OkMediaDownloadRequestExecutor.java @@ -0,0 +1,92 @@ +package me.chanjar.weixin.common.util.http.okhttp; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.lang3.StringUtils; + +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.bean.result.WxMediaUploadResult; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.fs.FileUtils; +import me.chanjar.weixin.common.util.http.MediaDownloadRequestExecutor; +import me.chanjar.weixin.common.util.http.RequestExecutor; +import me.chanjar.weixin.common.util.http.RequestHttp; +import okhttp3.*; + +/** + * Created by ecoolper on 2017/5/5. + */ +public class OkMediaDownloadRequestExecutor extends MediaDownloadRequestExecutor { + + + public OkMediaDownloadRequestExecutor(RequestHttp requestHttp, File tmpDirFile) { + super(requestHttp, tmpDirFile); + } + + @Override + public File execute(String uri, String queryParam) throws WxErrorException, IOException { + if (queryParam != null) { + if (uri.indexOf('?') == -1) { + uri += '?'; + } + uri += uri.endsWith("?") ? queryParam : '&' + queryParam; + } + + OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder().connectionPool(requestHttp.getRequestHttpClient()); + //设置代理 + if (requestHttp.getRequestHttpProxy() != null) { + clientBuilder.proxy(requestHttp.getRequestHttpProxy().getProxy()); + } + //设置授权 + clientBuilder.authenticator(new Authenticator() { + @Override + public Request authenticate(Route route, Response response) throws IOException { + String credential = Credentials.basic(requestHttp.getRequestHttpProxy().getProxyUsername(), requestHttp.getRequestHttpProxy().getProxyPassword()); + return response.request().newBuilder() + .header("Authorization", credential) + .build(); + } + }); + //得到httpClient + OkHttpClient client = clientBuilder.build(); + + Request request = new Request.Builder().url(uri).get().build(); + + Response response = client.newCall(request).execute(); + + String contentType = response.header("Content-Type"); + if (contentType != null && contentType.startsWith("application/json")) { + // application/json; encoding=utf-8 下载媒体文件出错 + throw new WxErrorException(WxError.fromJson(response.body().string())); + } + + String fileName = getFileName(response); + if (StringUtils.isBlank(fileName)) { + return null; + } + + InputStream inputStream = new ByteArrayInputStream(response.body().bytes()); + String[] nameAndExt = fileName.split("\\."); + return FileUtils.createTmpFile(inputStream, nameAndExt[0], nameAndExt[1], super.tmpDirFile); + } + + private String getFileName(Response response) throws WxErrorException { + String content = response.header("Content-disposition"); + if (content == null || content.length() == 0) { + throw new WxErrorException(WxError.newBuilder().setErrorMsg("无法获取到文件名").build()); + } + + Pattern p = Pattern.compile(".*filename=\"(.*)\""); + Matcher m = p.matcher(content); + if (m.matches()) { + return m.group(1); + } + throw new WxErrorException(WxError.newBuilder().setErrorMsg("无法获取到文件名").build()); + } + +} diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/okhttp/OkMediaUploadRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/okhttp/OkMediaUploadRequestExecutor.java new file mode 100644 index 00000000..b3808956 --- /dev/null +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/okhttp/OkMediaUploadRequestExecutor.java @@ -0,0 +1,56 @@ +package me.chanjar.weixin.common.util.http.okhttp; + +import java.io.File; +import java.io.IOException; + +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.bean.result.WxMediaUploadResult; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.MediaUploadRequestExecutor; +import me.chanjar.weixin.common.util.http.RequestExecutor; +import me.chanjar.weixin.common.util.http.RequestHttp; +import okhttp3.*; + +/** + * Created by ecoolper on 2017/5/5. + */ +public class OkMediaUploadRequestExecutor extends MediaUploadRequestExecutor { + + public OkMediaUploadRequestExecutor(RequestHttp requestHttp) { + super(requestHttp); + } + + @Override + public WxMediaUploadResult execute(String uri, File file) throws WxErrorException, IOException { + OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder().connectionPool(requestHttp.getRequestHttpClient()); + //设置代理 + if (requestHttp.getRequestHttpProxy() != null) { + clientBuilder.proxy(requestHttp.getRequestHttpProxy().getProxy()); + } + //设置授权 + clientBuilder.authenticator(new Authenticator() { + @Override + public Request authenticate(Route route, Response response) throws IOException { + String credential = Credentials.basic(requestHttp.getRequestHttpProxy().getProxyUsername(), requestHttp.getRequestHttpProxy().getProxyPassword()); + return response.request().newBuilder() + .header("Authorization", credential) + .build(); + } + }); + //得到httpClient + OkHttpClient client = clientBuilder.build(); + + RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), file); + RequestBody body = new MultipartBody.Builder().addFormDataPart("media", null, fileBody).build(); + Request request = new Request.Builder().url(uri).post(body).build(); + + Response response = client.newCall(request).execute(); + String responseContent = response.body().string(); + WxError error = WxError.fromJson(responseContent); + if (error.getErrorCode() != 0) { + throw new WxErrorException(error); + } + return WxMediaUploadResult.fromJson(responseContent); + } + +} diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/okhttp/OkSimpleGetRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/okhttp/OkSimpleGetRequestExecutor.java new file mode 100644 index 00000000..5d77bf7d --- /dev/null +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/okhttp/OkSimpleGetRequestExecutor.java @@ -0,0 +1,63 @@ +package me.chanjar.weixin.common.util.http.okhttp; + +import java.io.IOException; + +import jodd.http.HttpConnectionProvider; +import jodd.http.HttpRequest; +import jodd.http.HttpResponse; +import jodd.http.ProxyInfo; +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.RequestExecutor; +import me.chanjar.weixin.common.util.http.RequestHttp; +import me.chanjar.weixin.common.util.http.SimpleGetRequestExecutor; +import okhttp3.*; + +/** + * Created by ecoolper on 2017/5/4. + */ +public class OkSimpleGetRequestExecutor extends SimpleGetRequestExecutor { + + public OkSimpleGetRequestExecutor(RequestHttp requestHttp) { + super(requestHttp); + } + + @Override + public String execute(String uri, String queryParam) throws WxErrorException, IOException { + if (queryParam != null) { + if (uri.indexOf('?') == -1) { + uri += '?'; + } + uri += uri.endsWith("?") ? queryParam : '&' + queryParam; + } + + OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder().connectionPool(requestHttp.getRequestHttpClient()); + //设置代理 + if (requestHttp.getRequestHttpProxy() != null) { + clientBuilder.proxy(requestHttp.getRequestHttpProxy().getProxy()); + } + //设置授权 + clientBuilder.authenticator(new Authenticator() { + @Override + public Request authenticate(Route route, Response response) throws IOException { + String credential = Credentials.basic(requestHttp.getRequestHttpProxy().getProxyUsername(), requestHttp.getRequestHttpProxy().getProxyPassword()); + return response.request().newBuilder() + .header("Authorization", credential) + .build(); + } + }); + //得到httpClient + OkHttpClient client =clientBuilder.build(); + + Request request = new Request.Builder().url(uri).build(); + + Response response = client.newCall(request).execute(); + String responseContent = response.body().string(); + WxError error = WxError.fromJson(responseContent); + if (error.getErrorCode() != 0) { + throw new WxErrorException(error); + } + return responseContent; + } + +} diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/okhttp/OkSimplePostRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/okhttp/OkSimplePostRequestExecutor.java new file mode 100644 index 00000000..1fddcb26 --- /dev/null +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/okhttp/OkSimplePostRequestExecutor.java @@ -0,0 +1,59 @@ +package me.chanjar.weixin.common.util.http.okhttp; + +import java.io.IOException; + +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.RequestExecutor; +import me.chanjar.weixin.common.util.http.RequestHttp; +import me.chanjar.weixin.common.util.http.SimplePostRequestExecutor; +import okhttp3.*; + +/** + * Created by ecoolper on 2017/5/4. + */ +public class OkSimplePostRequestExecutor extends SimplePostRequestExecutor{ + + public OkSimplePostRequestExecutor(RequestHttp requestHttp) { + super(requestHttp); + } + + @Override + public String execute(String uri, String postEntity) throws WxErrorException, IOException { + ConnectionPool pool = requestHttp.getRequestHttpClient(); + final OkhttpProxyInfo proxyInfo = requestHttp.getRequestHttpProxy(); + + OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder().connectionPool(pool); + //设置代理 + if (proxyInfo != null) { + clientBuilder.proxy(proxyInfo.getProxy()); + } + //设置授权 + clientBuilder.authenticator(new Authenticator() { + @Override + public Request authenticate(Route route, Response response) throws IOException { + String credential = Credentials.basic(proxyInfo.getProxyUsername(), proxyInfo.getProxyPassword()); + return response.request().newBuilder() + .header("Authorization", credential) + .build(); + } + }); + //得到httpClient + OkHttpClient client = clientBuilder.build(); + + + MediaType mediaType = MediaType.parse("text/plain; charset=utf-8"); + RequestBody body = RequestBody.create(mediaType, postEntity); + + Request request = new Request.Builder().url(uri).post(body).build(); + + Response response = client.newCall(request).execute(); + String responseContent = response.body().string(); + WxError error = WxError.fromJson(responseContent); + if (error.getErrorCode() != 0) { + throw new WxErrorException(error); + } + return responseContent; + } + +} diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/impl/AbstractWxCpServiceImpl.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/impl/AbstractWxCpServiceImpl.java index 27928d8b..85065a71 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/impl/AbstractWxCpServiceImpl.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/impl/AbstractWxCpServiceImpl.java @@ -93,7 +93,7 @@ public abstract class AbstractWxCpServiceImpl implements WxCpService, Requ synchronized (this.globalJsapiTicketRefreshLock) { if (this.configStorage.isJsapiTicketExpired()) { String url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket"; - String responseContent = execute(new SimpleGetRequestExecutor(), url, null); + String responseContent = execute(SimpleGetRequestExecutor.create(this), url, null); JsonElement tmpJsonElement = new JsonParser().parse(responseContent); JsonObject tmpJsonObject = tmpJsonElement.getAsJsonObject(); String jsapiTicket = tmpJsonObject.get("ticket").getAsString(); @@ -187,14 +187,14 @@ public abstract class AbstractWxCpServiceImpl implements WxCpService, Requ @Override public WxMediaUploadResult mediaUpload(String mediaType, File file) throws WxErrorException { String url = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?type=" + mediaType; - return execute(new MediaUploadRequestExecutor(), url, file); + return execute(MediaUploadRequestExecutor.create(this), url, file); } @Override public File mediaDownload(String mediaId) throws WxErrorException { String url = "https://qyapi.weixin.qq.com/cgi-bin/media/get"; return execute( - new MediaDownloadRequestExecutor( + MediaDownloadRequestExecutor.create(this, this.configStorage.getTmpDirFile()), url, "media_id=" + mediaId); } @@ -204,7 +204,7 @@ public abstract class AbstractWxCpServiceImpl implements WxCpService, Requ public Integer departCreate(WxCpDepart depart) throws WxErrorException { String url = "https://qyapi.weixin.qq.com/cgi-bin/department/create"; String responseContent = execute( - new SimplePostRequestExecutor(), + SimplePostRequestExecutor.create(this), url, depart.toJson()); JsonElement tmpJsonElement = new JsonParser().parse(responseContent); @@ -475,12 +475,12 @@ public abstract class AbstractWxCpServiceImpl implements WxCpService, Requ @Override public String get(String url, String queryParam) throws WxErrorException { - return execute(new SimpleGetRequestExecutor(), url, queryParam); + return execute(SimpleGetRequestExecutor.create(this), url, queryParam); } @Override public String post(String url, String postData) throws WxErrorException { - return execute(new SimplePostRequestExecutor(), url, postData); + return execute(SimplePostRequestExecutor.create(this), url, postData); } /** @@ -530,7 +530,7 @@ public abstract class AbstractWxCpServiceImpl implements WxCpService, Requ String uriWithAccessToken = uri + (uri.contains("?") ? "&" : "?") + "access_token=" + accessToken; try { - T result = executor.execute(this, uriWithAccessToken, data); + T result = executor.execute(uriWithAccessToken, data); this.log.debug("\n[URL]: {}\n[PARAMS]: {}\n[RESPONSE]: {}", uriWithAccessToken, data, result); return result; } catch (WxErrorException e) { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpCardService.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpCardService.java index fbfeb6fc..715c3936 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpCardService.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpCardService.java @@ -8,7 +8,7 @@ import me.chanjar.weixin.mp.bean.result.WxMpCardResult; * 卡券相关接口 * @author YuJian(mgcnrx11@hotmail.com) on 01/11/2016 */ -public interface WxMpCardService { +public interface WxMpCardService { /** * 得到WxMpService diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpService.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpService.java index 8f03350b..da51c001 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpService.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpService.java @@ -4,6 +4,7 @@ import me.chanjar.weixin.common.bean.WxJsapiSignature; import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.common.util.http.MediaUploadRequestExecutor; import me.chanjar.weixin.common.util.http.RequestExecutor; +import me.chanjar.weixin.common.util.http.RequestHttp; import me.chanjar.weixin.mp.bean.*; import me.chanjar.weixin.mp.bean.result.*; @@ -414,5 +415,11 @@ public interface WxMpService { */ void initHttp(); + /** + * + * @return + */ + RequestHttp getRequestHttp(); + } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/AbstractWxMpServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/AbstractWxMpServiceImpl.java index 00880ffd..527f6fe2 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/AbstractWxMpServiceImpl.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/AbstractWxMpServiceImpl.java @@ -45,6 +45,7 @@ public abstract class AbstractWxMpServiceImpl implements WxMpService, Requ private int retrySleepMillis = 1000; private int maxRetryTimes = 5; + @Override public boolean checkSignature(String timestamp, String nonce, String signature) { try { @@ -71,7 +72,7 @@ public abstract class AbstractWxMpServiceImpl implements WxMpService, Requ } if (this.getWxMpConfigStorage().isJsapiTicketExpired()) { - String responseContent = execute(new SimpleGetRequestExecutor(), WxMpService.GET_JSAPI_TICKET_URL, null); + String responseContent = execute(SimpleGetRequestExecutor.create(this), WxMpService.GET_JSAPI_TICKET_URL, null); JsonElement tmpJsonElement = JSON_PARSER.parse(responseContent); JsonObject tmpJsonObject = tmpJsonElement.getAsJsonObject(); String jsapiTicket = tmpJsonObject.get("ticket").getAsString(); @@ -165,8 +166,8 @@ public abstract class AbstractWxMpServiceImpl implements WxMpService, Requ private WxMpOAuth2AccessToken getOAuth2AccessToken(String url) throws WxErrorException { try { - RequestExecutor executor = new SimpleGetRequestExecutor(); - String responseText = executor.execute(this, url, null); + RequestExecutor executor = SimpleGetRequestExecutor.create(this); + String responseText = executor.execute(url, null); return WxMpOAuth2AccessToken.fromJson(responseText); } catch (IOException e) { throw new RuntimeException(e); @@ -194,8 +195,8 @@ public abstract class AbstractWxMpServiceImpl implements WxMpService, Requ String url = String.format(WxMpService.OAUTH2_USERINFO_URL, oAuth2AccessToken.getAccessToken(), oAuth2AccessToken.getOpenId(), lang); try { - RequestExecutor executor = new SimpleGetRequestExecutor(); - String responseText = executor.execute(this, url, null); + RequestExecutor executor = SimpleGetRequestExecutor.create(this); + String responseText = executor.execute(url, null); return WxMpUser.fromJson(responseText); } catch (IOException e) { throw new RuntimeException(e); @@ -207,8 +208,8 @@ public abstract class AbstractWxMpServiceImpl implements WxMpService, Requ String url = String.format(WxMpService.OAUTH2_VALIDATE_TOKEN_URL, oAuth2AccessToken.getAccessToken(), oAuth2AccessToken.getOpenId()); try { - RequestExecutor executor = new SimpleGetRequestExecutor(); - executor.execute(this, url, null); + RequestExecutor executor = SimpleGetRequestExecutor.create(this); + executor.execute(url, null); } catch (IOException e) { throw new RuntimeException(e); } catch (WxErrorException e) { @@ -231,12 +232,12 @@ public abstract class AbstractWxMpServiceImpl implements WxMpService, Requ @Override public String get(String url, String queryParam) throws WxErrorException { - return execute(new SimpleGetRequestExecutor(), url, queryParam); + return execute(SimpleGetRequestExecutor.create(this), url, queryParam); } @Override public String post(String url, String postData) throws WxErrorException { - return execute(new SimplePostRequestExecutor(), url, postData); + return execute(SimplePostRequestExecutor.create(this), url, postData); } /** @@ -283,7 +284,7 @@ public abstract class AbstractWxMpServiceImpl implements WxMpService, Requ String uriWithAccessToken = uri + (uri.contains("?") ? "&" : "?") + "access_token=" + accessToken; try { - T result = executor.execute(this, uriWithAccessToken, data); + T result = executor.execute(uriWithAccessToken, data); this.log.debug("\n[URL]: {}\n[PARAMS]: {}\n[RESPONSE]: {}", uriWithAccessToken, data, result); return result; } catch (WxErrorException e) { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpCardServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpCardServiceImpl.java index 4db5e0e7..ce080330 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpCardServiceImpl.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpCardServiceImpl.java @@ -15,8 +15,6 @@ import me.chanjar.weixin.mp.api.WxMpCardService; import me.chanjar.weixin.mp.api.WxMpService; import me.chanjar.weixin.mp.bean.result.WxMpCardResult; import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; -import org.apache.http.HttpHost; -import org.apache.http.impl.client.CloseableHttpClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -26,7 +24,7 @@ import java.util.concurrent.locks.Lock; /** * Created by Binary Wang on 2016/7/27. */ -public class WxMpCardServiceImpl implements WxMpCardService { +public class WxMpCardServiceImpl implements WxMpCardService { private final Logger log = LoggerFactory.getLogger(WxMpCardServiceImpl.class); @@ -77,7 +75,7 @@ public class WxMpCardServiceImpl implements WxMpCardService map = new HashMap<>(); map.put("openid_list", openidList); String url = API_BLACKLIST_PREFIX + "/batchblacklist"; - this.wxMpService.execute(new SimplePostRequestExecutor(), url, new Gson().toJson(map)); + this.wxMpService.execute(SimplePostRequestExecutor.create(this.wxMpService.getRequestHttp()), url, new Gson().toJson(map)); } @Override @@ -45,6 +45,6 @@ public class WxMpUserBlacklistServiceImpl implements WxMpUserBlacklistService { Map map = new HashMap<>(); map.put("openid_list", openidList); String url = API_BLACKLIST_PREFIX + "/batchunblacklist"; - this.wxMpService.execute(new SimplePostRequestExecutor(), url, new Gson().toJson(map)); + this.wxMpService.execute(SimplePostRequestExecutor.create(this.wxMpService.getRequestHttp()), url, new Gson().toJson(map)); } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/apache/WxMpServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/apache/WxMpServiceImpl.java index 835fbe18..d0991a5b 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/apache/WxMpServiceImpl.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/apache/WxMpServiceImpl.java @@ -71,6 +71,11 @@ public class WxMpServiceImpl extends AbstractWxMpServiceImpl { +public abstract class MaterialDeleteRequestExecutor implements RequestExecutor { + protected RequestHttp requestHttp; - - public MaterialDeleteRequestExecutor() { - super(); - } - - @Override - public Boolean executeApache(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, - String materialId) throws WxErrorException, IOException { - HttpPost httpPost = new HttpPost(uri); - if (httpProxy != null) { - RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build(); - httpPost.setConfig(config); - } - - Map params = new HashMap<>(); - params.put("media_id", materialId); - httpPost.setEntity(new StringEntity(WxGsonBuilder.create().toJson(params))); - try (CloseableHttpResponse response = httpclient.execute(httpPost)) { - String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); - WxError error = WxError.fromJson(responseContent); - if (error.getErrorCode() != 0) { - throw new WxErrorException(error); - } else { - return true; - } - } finally { - httpPost.releaseConnection(); - } - } - - - @Override - public Boolean executeJodd(HttpConnectionProvider provider, ProxyInfo proxyInfo, String uri, String materialId) throws WxErrorException, IOException { - HttpRequest request = HttpRequest.post(uri); - if (proxyInfo != null) { - provider.useProxy(proxyInfo); - } - request.withConnectionProvider(provider); - - request.query("media_id", materialId); - HttpResponse response = request.send(); - String responseContent = response.bodyText(); - WxError error = WxError.fromJson(responseContent); - if (error.getErrorCode() != 0) { - throw new WxErrorException(error); - } else { - return true; - } + public MaterialDeleteRequestExecutor(RequestHttp requestHttp){ + this.requestHttp =requestHttp; } - @Override - public Boolean executeOkhttp(ConnectionPool pool, final OkhttpProxyInfo proxyInfo, String uri, String materialId) throws WxErrorException, IOException { - OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder().connectionPool(pool); - //设置代理 - if (proxyInfo != null) { - clientBuilder.proxy(proxyInfo.getProxy()); - } - //设置授权 - clientBuilder.authenticator(new Authenticator() { - @Override - public Request authenticate(Route route, Response response) throws IOException { - String credential = Credentials.basic(proxyInfo.getProxyUsername(), proxyInfo.getProxyPassword()); - return response.request().newBuilder() - .header("Authorization", credential) - .build(); - } - }); - //得到httpClient - OkHttpClient client = clientBuilder.build(); - - RequestBody requestBody = new FormBody.Builder().add("media_id", materialId).build(); - Request request = new Request.Builder().url(uri).post(requestBody).build(); - Response response = client.newCall(request).execute(); - String responseContent = response.body().string(); - WxError error = WxError.fromJson(responseContent); - if (error.getErrorCode() != 0) { - throw new WxErrorException(error); - } else { - return true; + public static RequestExecutor create(RequestHttp requestHttp){ + switch (requestHttp.getRequestType()){ + case apacheHttp: + return new ApacheMaterialDeleteRequestExecutor(requestHttp); + case joddHttp: + return new JoddMaterialDeleteRequestExecutor(requestHttp); + case okHttp: + return new OkhttpMaterialDeleteRequestExecutor(requestHttp); + default: + return null; } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialNewsInfoRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialNewsInfoRequestExecutor.java index de5f2342..92188b2a 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialNewsInfoRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialNewsInfoRequestExecutor.java @@ -6,7 +6,6 @@ import jodd.http.HttpResponse; import jodd.http.ProxyInfo; import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.common.util.http.AbstractRequestExecutor; import me.chanjar.weixin.common.util.http.RequestExecutor; import me.chanjar.weixin.common.util.http.RequestHttp; import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; @@ -15,6 +14,9 @@ import me.chanjar.weixin.common.util.http.okhttp.OkhttpProxyInfo; import me.chanjar.weixin.common.util.json.WxGsonBuilder; import me.chanjar.weixin.mp.bean.material.WxMpMaterialNews; +import me.chanjar.weixin.mp.util.http.apache.ApacheMaterialNewsInfoRequestExecutor; +import me.chanjar.weixin.mp.util.http.jodd.JoddMaterialNewsInfoRequestExecutor; +import me.chanjar.weixin.mp.util.http.okhttp.OkhttpMaterialNewsInfoRequestExecutor; import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; import okhttp3.*; @@ -29,88 +31,24 @@ import java.io.IOException; import java.util.HashMap; import java.util.Map; -public class MaterialNewsInfoRequestExecutor extends AbstractRequestExecutor { +public abstract class MaterialNewsInfoRequestExecutor implements RequestExecutor { + protected RequestHttp requestHttp; - public MaterialNewsInfoRequestExecutor() { - super(); + public MaterialNewsInfoRequestExecutor(RequestHttp requestHttp){ + this.requestHttp =requestHttp; } - @Override - public WxMpMaterialNews executeApache(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String materialId) throws WxErrorException, IOException { - HttpPost httpPost = new HttpPost(uri); - if (httpProxy != null) { - RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build(); - httpPost.setConfig(config); - } - - Map params = new HashMap<>(); - params.put("media_id", materialId); - httpPost.setEntity(new StringEntity(WxGsonBuilder.create().toJson(params))); - try (CloseableHttpResponse response = httpclient.execute(httpPost)) { - String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); - WxError error = WxError.fromJson(responseContent); - if (error.getErrorCode() != 0) { - throw new WxErrorException(error); - } else { - return WxMpGsonBuilder.create().fromJson(responseContent, WxMpMaterialNews.class); - } - } finally { - httpPost.releaseConnection(); - } - } - - - @Override - public WxMpMaterialNews executeJodd(HttpConnectionProvider httpclient, ProxyInfo httpProxy, String uri, String materialId) throws WxErrorException, IOException { - HttpRequest request = HttpRequest.post(uri); - if (httpProxy != null) { - httpclient.useProxy(httpProxy); - } - request.withConnectionProvider(httpclient); - - request.query("media_id", materialId); - HttpResponse response = request.send(); - - String responseContent = response.bodyText(); - WxError error = WxError.fromJson(responseContent); - if (error.getErrorCode() != 0) { - throw new WxErrorException(error); - } else { - return WxMpGsonBuilder.create().fromJson(responseContent, WxMpMaterialNews.class); - } - } - - @Override - public WxMpMaterialNews executeOkhttp(ConnectionPool pool, final OkhttpProxyInfo proxyInfo, String uri, String materialId) throws WxErrorException, IOException { - OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder().connectionPool(pool); - //设置代理 - if (proxyInfo != null) { - clientBuilder.proxy(proxyInfo.getProxy()); - } - //设置授权 - clientBuilder.authenticator(new Authenticator() { - @Override - public Request authenticate(Route route, Response response) throws IOException { - String credential = Credentials.basic(proxyInfo.getProxyUsername(), proxyInfo.getProxyPassword()); - return response.request().newBuilder() - .header("Authorization", credential) - .build(); - } - }); - //得到httpClient - OkHttpClient client = clientBuilder.build(); - - RequestBody requestBody = new FormBody.Builder().add("media_id", materialId).build(); - Request request = new Request.Builder().url(uri).post(requestBody).build(); - - Response response = client.newCall(request).execute(); - String responseContent = response.body().string(); - - WxError error = WxError.fromJson(responseContent); - if (error.getErrorCode() != 0) { - throw new WxErrorException(error); - } else { - return WxMpGsonBuilder.create().fromJson(responseContent, WxMpMaterialNews.class); + public static RequestExecutor create(RequestHttp requestHttp){ + switch (requestHttp.getRequestType()){ + case apacheHttp: + return new ApacheMaterialNewsInfoRequestExecutor(requestHttp); + case joddHttp: + return new JoddMaterialNewsInfoRequestExecutor(requestHttp); + case okHttp: + return new OkhttpMaterialNewsInfoRequestExecutor(requestHttp); + default: + //TODO 需要优化抛出异常 + return null; } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialUploadRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialUploadRequestExecutor.java index 772684ab..54d1d0e7 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialUploadRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialUploadRequestExecutor.java @@ -6,7 +6,6 @@ import jodd.http.HttpResponse; import jodd.http.ProxyInfo; import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.common.util.http.AbstractRequestExecutor; import me.chanjar.weixin.common.util.http.RequestExecutor; import me.chanjar.weixin.common.util.http.RequestHttp; import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; @@ -16,6 +15,9 @@ import me.chanjar.weixin.common.util.http.okhttp.OkhttpProxyInfo; import me.chanjar.weixin.common.util.json.WxGsonBuilder; import me.chanjar.weixin.mp.bean.material.WxMpMaterial; import me.chanjar.weixin.mp.bean.material.WxMpMaterialUploadResult; +import me.chanjar.weixin.mp.util.http.apache.ApacheMaterialUploadRequestExecutor; +import me.chanjar.weixin.mp.util.http.jodd.JoddMaterialUploadRequestExecutor; +import me.chanjar.weixin.mp.util.http.okhttp.OkhttpMaterialUploadRequestExecutor; import okhttp3.*; import org.apache.http.HttpHost; @@ -32,127 +34,22 @@ import java.io.FileNotFoundException; import java.io.IOException; import java.util.Map; -public class MaterialUploadRequestExecutor extends AbstractRequestExecutor { - - @Override - public WxMpMaterialUploadResult executeJodd(HttpConnectionProvider provider, ProxyInfo httpProxy, String uri, WxMpMaterial material) throws WxErrorException, IOException { - HttpRequest request = HttpRequest.post(uri); - if (httpProxy != null) { - provider.useProxy(httpProxy); - } - request.withConnectionProvider(provider); - - if (material == null) { - throw new WxErrorException(WxError.newBuilder().setErrorMsg("非法请求,material参数为空").build()); - } - - File file = material.getFile(); - if (file == null || !file.exists()) { - throw new FileNotFoundException(); - } - request.form("media", file); - Map form = material.getForm(); - if (material.getForm() != null) { - request.form("description", WxGsonBuilder.create().toJson(form)); - } - - HttpResponse response = request.send(); - String responseContent = response.bodyText(); - WxError error = WxError.fromJson(responseContent); - if (error.getErrorCode() != 0) { - throw new WxErrorException(error); - } else { - return WxMpMaterialUploadResult.fromJson(responseContent); - } - } - - @Override - public WxMpMaterialUploadResult executeOkhttp(ConnectionPool pool, final OkhttpProxyInfo proxyInfo, String uri, WxMpMaterial material) throws WxErrorException, IOException { - OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder().connectionPool(pool); - //设置代理 - if (proxyInfo != null) { - clientBuilder.proxy(proxyInfo.getProxy()); - } - //设置授权 - clientBuilder.authenticator(new Authenticator() { - @Override - public Request authenticate(Route route, Response response) throws IOException { - String credential = Credentials.basic(proxyInfo.getProxyUsername(), proxyInfo.getProxyPassword()); - return response.request().newBuilder() - .header("Authorization", credential) - .build(); - } - }); - //得到httpClient - OkHttpClient client = clientBuilder.build(); - - - if (material == null) { - throw new WxErrorException(WxError.newBuilder().setErrorMsg("非法请求,material参数为空").build()); - } - - File file = material.getFile(); - if (file == null || !file.exists()) { - throw new FileNotFoundException(); - } - RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), file); - MultipartBody.Builder bodyBuilder = new MultipartBody.Builder().addFormDataPart("media", null, fileBody); - Map form = material.getForm(); - if (material.getForm() != null) { - bodyBuilder.addFormDataPart("description", WxGsonBuilder.create().toJson(form)); - } - RequestBody body =bodyBuilder.build(); - Request request = new Request.Builder().url(uri).post(body).build(); - Response response = client.newCall(request).execute(); - String responseContent = response.body().string(); - WxError error = WxError.fromJson(responseContent); - if (error.getErrorCode() != 0) { - throw new WxErrorException(error); - } else { - return WxMpMaterialUploadResult.fromJson(responseContent); - } +public abstract class MaterialUploadRequestExecutor implements RequestExecutor { + protected RequestHttp requestHttp; + public MaterialUploadRequestExecutor(RequestHttp requestHttp){ + this.requestHttp =requestHttp; } - @Override - public WxMpMaterialUploadResult executeApache(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, - WxMpMaterial material) throws WxErrorException, IOException { - HttpPost httpPost = new HttpPost(uri); - if (httpProxy != null) { - RequestConfig response = RequestConfig.custom().setProxy(httpProxy).build(); - httpPost.setConfig(response); - } - - if (material == null) { - throw new WxErrorException(WxError.newBuilder().setErrorMsg("非法请求,material参数为空").build()); - } - - File file = material.getFile(); - if (file == null || !file.exists()) { - throw new FileNotFoundException(); - } - - MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); - multipartEntityBuilder - .addBinaryBody("media", file) - .setMode(HttpMultipartMode.RFC6532); - Map form = material.getForm(); - if (material.getForm() != null) { - multipartEntityBuilder.addTextBody("description", WxGsonBuilder.create().toJson(form)); - } - - httpPost.setEntity(multipartEntityBuilder.build()); - httpPost.setHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString()); - - try (CloseableHttpResponse response = httpclient.execute(httpPost)) { - String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); - WxError error = WxError.fromJson(responseContent); - if (error.getErrorCode() != 0) { - throw new WxErrorException(error); - } else { - return WxMpMaterialUploadResult.fromJson(responseContent); - } - } finally { - httpPost.releaseConnection(); + public static RequestExecutor create(RequestHttp requestHttp){ + switch (requestHttp.getRequestType()){ + case apacheHttp: + return new ApacheMaterialUploadRequestExecutor(requestHttp); + case joddHttp: + return new JoddMaterialUploadRequestExecutor(requestHttp); + case okHttp: + return new OkhttpMaterialUploadRequestExecutor(requestHttp); + default: + return null; } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialVideoInfoRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialVideoInfoRequestExecutor.java index 3c481f7c..c042d261 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialVideoInfoRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialVideoInfoRequestExecutor.java @@ -6,7 +6,6 @@ import jodd.http.HttpResponse; import jodd.http.ProxyInfo; import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.common.util.http.AbstractRequestExecutor; import me.chanjar.weixin.common.util.http.RequestExecutor; import me.chanjar.weixin.common.util.http.RequestHttp; import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; @@ -14,8 +13,10 @@ import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; import me.chanjar.weixin.common.util.http.okhttp.OkhttpProxyInfo; import me.chanjar.weixin.common.util.json.WxGsonBuilder; -import me.chanjar.weixin.mp.bean.material.WxMediaImgUploadResult; import me.chanjar.weixin.mp.bean.material.WxMpMaterialVideoInfoResult; +import me.chanjar.weixin.mp.util.http.apache.ApacheMaterialVideoInfoRequestExecutor; +import me.chanjar.weixin.mp.util.http.jodd.JoddMaterialVideoInfoRequestExecutor; +import me.chanjar.weixin.mp.util.http.okhttp.OkhttpMaterialVideoInfoRequestExecutor; import okhttp3.*; import org.apache.http.HttpHost; @@ -29,87 +30,23 @@ import java.io.IOException; import java.util.HashMap; import java.util.Map; -public class MaterialVideoInfoRequestExecutor extends AbstractRequestExecutor { - - public MaterialVideoInfoRequestExecutor() { - super(); - } - - @Override - public WxMpMaterialVideoInfoResult executeJodd(HttpConnectionProvider provider, ProxyInfo proxyInfo, String uri, String materialId) throws WxErrorException, IOException { - HttpRequest request = HttpRequest.post(uri); - if (proxyInfo != null) { - provider.useProxy(proxyInfo); - } - request.withConnectionProvider(provider); - - request.query("media_id", materialId); - HttpResponse response = request.send(); - String responseContent = response.bodyText(); - WxError error = WxError.fromJson(responseContent); - if (error.getErrorCode() != 0) { - throw new WxErrorException(error); - } else { - return WxMpMaterialVideoInfoResult.fromJson(responseContent); - } - } - - @Override - public WxMpMaterialVideoInfoResult executeOkhttp(ConnectionPool pool, final OkhttpProxyInfo proxyInfo, String uri, String materialId) throws WxErrorException, IOException { - OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder().connectionPool(pool); - //设置代理 - if (proxyInfo != null) { - clientBuilder.proxy(proxyInfo.getProxy()); - } - //设置授权 - clientBuilder.authenticator(new Authenticator() { - @Override - public Request authenticate(Route route, Response response) throws IOException { - String credential = Credentials.basic(proxyInfo.getProxyUsername(), proxyInfo.getProxyPassword()); - return response.request().newBuilder() - .header("Authorization", credential) - .build(); - } - }); - //得到httpClient - OkHttpClient client = clientBuilder.build(); - - RequestBody requestBody =new FormBody.Builder().add("media_id", materialId).build(); - Request request = new Request.Builder().url(uri).post(requestBody).build(); - Response response = client.newCall(request).execute(); - String responseContent = response.body().string(); - WxError error = WxError.fromJson(responseContent); - if (error.getErrorCode() != 0) { - throw new WxErrorException(error); - } else { - return WxMpMaterialVideoInfoResult.fromJson(responseContent); - } +public abstract class MaterialVideoInfoRequestExecutor implements RequestExecutor { + protected RequestHttp requestHttp; + public MaterialVideoInfoRequestExecutor(RequestHttp requestHttp){ + this.requestHttp =requestHttp; } - @Override - public WxMpMaterialVideoInfoResult executeApache(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, - String materialId) throws WxErrorException, IOException { - HttpPost httpPost = new HttpPost(uri); - if (httpProxy != null) { - RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build(); - httpPost.setConfig(config); - } - - Map params = new HashMap<>(); - params.put("media_id", materialId); - httpPost.setEntity(new StringEntity(WxGsonBuilder.create().toJson(params))); - try (CloseableHttpResponse response = httpclient.execute(httpPost)) { - String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); - WxError error = WxError.fromJson(responseContent); - if (error.getErrorCode() != 0) { - throw new WxErrorException(error); - } else { - return WxMpMaterialVideoInfoResult.fromJson(responseContent); - } - } finally { - httpPost.releaseConnection(); + public static RequestExecutor create(RequestHttp requestHttp){ + switch (requestHttp.getRequestType()){ + case apacheHttp: + return new ApacheMaterialVideoInfoRequestExecutor(requestHttp); + case joddHttp: + return new JoddMaterialVideoInfoRequestExecutor(requestHttp); + case okHttp: + return new OkhttpMaterialVideoInfoRequestExecutor(requestHttp); + default: + return null; } } - } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialVoiceAndImageDownloadRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialVoiceAndImageDownloadRequestExecutor.java index d536223c..75255346 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialVoiceAndImageDownloadRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialVoiceAndImageDownloadRequestExecutor.java @@ -7,13 +7,14 @@ import jodd.http.ProxyInfo; import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.common.util.http.AbstractRequestExecutor; import me.chanjar.weixin.common.util.http.RequestExecutor; import me.chanjar.weixin.common.util.http.RequestHttp; import me.chanjar.weixin.common.util.http.apache.InputStreamResponseHandler; import me.chanjar.weixin.common.util.http.okhttp.OkhttpProxyInfo; import me.chanjar.weixin.common.util.json.WxGsonBuilder; -import me.chanjar.weixin.mp.bean.material.WxMediaImgUploadResult; +import me.chanjar.weixin.mp.util.http.apache.ApacheMaterialVoiceAndImageDownloadRequestExecutor; +import me.chanjar.weixin.mp.util.http.jodd.JoddMaterialVoiceAndImageDownloadRequestExecutor; +import me.chanjar.weixin.mp.util.http.okhttp.OkhttpMaterialVoiceAndImageDownloadRequestExecutor; import okhttp3.*; import org.apache.commons.io.IOUtils; @@ -31,119 +32,27 @@ import java.io.InputStream; import java.util.HashMap; import java.util.Map; -public class MaterialVoiceAndImageDownloadRequestExecutor extends AbstractRequestExecutor { +public abstract class MaterialVoiceAndImageDownloadRequestExecutor implements RequestExecutor { + protected RequestHttp requestHttp; + protected File tmpDirFile; - public MaterialVoiceAndImageDownloadRequestExecutor() { - super(); - } - - public MaterialVoiceAndImageDownloadRequestExecutor(File tmpDirFile) { - super(); - } - - - @Override - public InputStream executeJodd(HttpConnectionProvider provider, ProxyInfo proxyInfo, String uri, String materialId) throws WxErrorException, IOException { - HttpRequest request = HttpRequest.post(uri); - if (proxyInfo != null) { - provider.useProxy(proxyInfo); - } - request.withConnectionProvider(provider); - - request.query("media_id", materialId); - HttpResponse response = request.send(); - try (InputStream inputStream = new ByteArrayInputStream(response.bodyBytes())) { - // 下载媒体文件出错 - byte[] responseContent = IOUtils.toByteArray(inputStream); - String responseContentString = new String(responseContent, "UTF-8"); - if (responseContentString.length() < 100) { - try { - WxError wxError = WxGsonBuilder.create().fromJson(responseContentString, WxError.class); - if (wxError.getErrorCode() != 0) { - throw new WxErrorException(wxError); - } - } catch (com.google.gson.JsonSyntaxException ex) { - return new ByteArrayInputStream(responseContent); - } - } - return new ByteArrayInputStream(responseContent); - } + public MaterialVoiceAndImageDownloadRequestExecutor(RequestHttp requestHttp, File tmpDirFile) { + this.requestHttp = requestHttp; + this.tmpDirFile = tmpDirFile; } - @Override - public InputStream executeOkhttp(ConnectionPool pool, final OkhttpProxyInfo proxyInfo, String uri, String materialId) throws WxErrorException, IOException { - OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder().connectionPool(pool); - //设置代理 - if (proxyInfo != null) { - clientBuilder.proxy(proxyInfo.getProxy()); - } - //设置授权 - clientBuilder.authenticator(new Authenticator() { - @Override - public Request authenticate(Route route, Response response) throws IOException { - String credential = Credentials.basic(proxyInfo.getProxyUsername(), proxyInfo.getProxyPassword()); - return response.request().newBuilder() - .header("Authorization", credential) - .build(); - } - }); - //得到httpClient - OkHttpClient client = clientBuilder.build(); - - RequestBody requestBody = new FormBody.Builder().add("media_id", materialId).build(); - Request request = new Request.Builder().url(uri).get().post(requestBody).build(); - Response response = client.newCall(request).execute(); - - try (InputStream inputStream = new ByteArrayInputStream(response.body().bytes())) { - - // 下载媒体文件出错 - byte[] responseContent = IOUtils.toByteArray(inputStream); - String responseContentString = new String(responseContent, "UTF-8"); - if (responseContentString.length() < 100) { - try { - WxError wxError = WxGsonBuilder.create().fromJson(responseContentString, WxError.class); - if (wxError.getErrorCode() != 0) { - throw new WxErrorException(wxError); - } - } catch (com.google.gson.JsonSyntaxException ex) { - return new ByteArrayInputStream(responseContent); - } - } - return new ByteArrayInputStream(responseContent); - } - } - - @Override - public InputStream executeApache(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, - String materialId) throws WxErrorException, IOException { - HttpPost httpPost = new HttpPost(uri); - if (httpProxy != null) { - RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build(); - httpPost.setConfig(config); - } - Map params = new HashMap<>(); - params.put("media_id", materialId); - httpPost.setEntity(new StringEntity(WxGsonBuilder.create().toJson(params))); - try (CloseableHttpResponse response = httpclient.execute(httpPost); - InputStream inputStream = InputStreamResponseHandler.INSTANCE.handleResponse(response);) { - // 下载媒体文件出错 - byte[] responseContent = IOUtils.toByteArray(inputStream); - String responseContentString = new String(responseContent, "UTF-8"); - if (responseContentString.length() < 100) { - try { - WxError wxError = WxGsonBuilder.create().fromJson(responseContentString, WxError.class); - if (wxError.getErrorCode() != 0) { - throw new WxErrorException(wxError); - } - } catch (com.google.gson.JsonSyntaxException ex) { - return new ByteArrayInputStream(responseContent); - } - } - return new ByteArrayInputStream(responseContent); - } finally { - httpPost.releaseConnection(); + public static RequestExecutor create(RequestHttp requestHttp, File tmpDirFile) { + switch (requestHttp.getRequestType()) { + case apacheHttp: + return new ApacheMaterialVoiceAndImageDownloadRequestExecutor(requestHttp, tmpDirFile); + case joddHttp: + return new JoddMaterialVoiceAndImageDownloadRequestExecutor(requestHttp, tmpDirFile); + case okHttp: + return new OkhttpMaterialVoiceAndImageDownloadRequestExecutor(requestHttp, tmpDirFile); + default: + return null; } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MediaImgUploadRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MediaImgUploadRequestExecutor.java index 4232f333..f4713afd 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MediaImgUploadRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MediaImgUploadRequestExecutor.java @@ -5,13 +5,8 @@ import jodd.http.HttpRequest; import jodd.http.HttpResponse; import jodd.http.ProxyInfo; -import jodd.util.MimeTypes; - import me.chanjar.weixin.common.bean.result.WxError; -import me.chanjar.weixin.common.bean.result.WxMediaUploadResult; import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.common.util.fs.FileUtils; -import me.chanjar.weixin.common.util.http.AbstractRequestExecutor; import me.chanjar.weixin.common.util.http.RequestExecutor; import me.chanjar.weixin.common.util.http.RequestHttp; import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; @@ -19,6 +14,9 @@ import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; import me.chanjar.weixin.common.util.http.okhttp.OkhttpProxyInfo; import me.chanjar.weixin.mp.bean.material.WxMediaImgUploadResult; +import me.chanjar.weixin.mp.util.http.apache.ApacheMediaImgUploadRequestExecutor; +import me.chanjar.weixin.mp.util.http.jodd.JoddMediaImgUploadRequestExecutor; +import me.chanjar.weixin.mp.util.http.okhttp.OkhttpMediaImgUploadRequestExecutor; import okhttp3.*; import org.apache.http.HttpEntity; @@ -31,104 +29,28 @@ import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; -import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; -import java.io.InputStream; -import java.util.UUID; /** * @author miller */ -public class MediaImgUploadRequestExecutor extends AbstractRequestExecutor { - - @Override - public WxMediaImgUploadResult executeJodd(HttpConnectionProvider provider, ProxyInfo proxyInfo, String uri, File data) throws WxErrorException, IOException { - if (data == null) { - throw new WxErrorException(WxError.newBuilder().setErrorMsg("文件对象为空").build()); - } - - HttpRequest request = HttpRequest.post(uri); - if (proxyInfo != null) { - provider.useProxy(proxyInfo); - } - request.withConnectionProvider(provider); - - request.form("media", data); - HttpResponse response = request.send(); - String responseContent = response.bodyText(); - WxError error = WxError.fromJson(responseContent); - if (error.getErrorCode() != 0) { - throw new WxErrorException(error); - } - - return WxMediaImgUploadResult.fromJson(responseContent); - } - - @Override - public WxMediaImgUploadResult executeOkhttp(ConnectionPool pool, final OkhttpProxyInfo proxyInfo, String uri, File data) throws WxErrorException, IOException { - OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder().connectionPool(pool); - //设置代理 - if (proxyInfo != null) { - clientBuilder.proxy(proxyInfo.getProxy()); - } - //设置授权 - clientBuilder.authenticator(new Authenticator() { - @Override - public Request authenticate(Route route, Response response) throws IOException { - String credential = Credentials.basic(proxyInfo.getProxyUsername(), proxyInfo.getProxyPassword()); - return response.request().newBuilder() - .header("Authorization", credential) - .build(); - } - }); - //得到httpClient - OkHttpClient client = clientBuilder.build(); - - RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), data); - RequestBody body = new MultipartBody.Builder().addFormDataPart("media", null, fileBody).build(); - Request request = new Request.Builder().url(uri).post(body).build(); - - Response response = client.newCall(request).execute(); - String responseContent = response.body().string(); - WxError error = WxError.fromJson(responseContent); - if (error.getErrorCode() != 0) { - throw new WxErrorException(error); - } - - return WxMediaImgUploadResult.fromJson(responseContent); +public abstract class MediaImgUploadRequestExecutor implements RequestExecutor { + protected RequestHttp requestHttp; + public MediaImgUploadRequestExecutor(RequestHttp requestHttp){ + this.requestHttp =requestHttp; } - @Override - public WxMediaImgUploadResult executeApache(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, - File data) throws WxErrorException, IOException { - - if (data == null) { - throw new WxErrorException(WxError.newBuilder().setErrorMsg("文件对象为空").build()); - } - - HttpPost httpPost = new HttpPost(uri); - if (httpProxy != null) { - RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build(); - httpPost.setConfig(config); - } - - HttpEntity entity = MultipartEntityBuilder - .create() - .addBinaryBody("media", data) - .setMode(HttpMultipartMode.RFC6532) - .build(); - httpPost.setEntity(entity); - httpPost.setHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString()); - - try (CloseableHttpResponse response = httpclient.execute(httpPost)) { - String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); - WxError error = WxError.fromJson(responseContent); - if (error.getErrorCode() != 0) { - throw new WxErrorException(error); - } - - return WxMediaImgUploadResult.fromJson(responseContent); + public static RequestExecutor create(RequestHttp requestHttp){ + switch (requestHttp.getRequestType()){ + case apacheHttp: + return new ApacheMediaImgUploadRequestExecutor(requestHttp); + case joddHttp: + return new JoddMediaImgUploadRequestExecutor(requestHttp); + case okHttp: + return new OkhttpMediaImgUploadRequestExecutor(requestHttp); + default: + return null; } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/QrCodeRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/QrCodeRequestExecutor.java index d37d0bb9..151a20e4 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/QrCodeRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/QrCodeRequestExecutor.java @@ -9,13 +9,16 @@ import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.common.util.fs.FileUtils; -import me.chanjar.weixin.common.util.http.AbstractRequestExecutor; +import me.chanjar.weixin.common.util.http.RequestExecutor; import me.chanjar.weixin.common.util.http.RequestHttp; import me.chanjar.weixin.common.util.http.apache.InputStreamResponseHandler; import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; import me.chanjar.weixin.common.util.http.okhttp.OkhttpProxyInfo; import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket; +import me.chanjar.weixin.mp.util.http.apache.ApacheQrCodeRequestExecutor; +import me.chanjar.weixin.mp.util.http.jodd.JoddQrCodeRequestExecutor; +import me.chanjar.weixin.mp.util.http.okhttp.OkhttpQrCodeRequestExecutor; import okhttp3.*; import org.apache.http.Header; @@ -38,102 +41,25 @@ import java.util.UUID; * * @author chanjarster */ -public class QrCodeRequestExecutor extends AbstractRequestExecutor { +public abstract class QrCodeRequestExecutor implements RequestExecutor { + protected RequestHttp requestHttp; -@Override - public File executeJodd(HttpConnectionProvider provider, ProxyInfo proxyInfo, String uri, WxMpQrCodeTicket ticket) throws WxErrorException, IOException { - if (ticket != null) { - if (uri.indexOf('?') == -1) { - uri += '?'; - } - uri += uri.endsWith("?") - ? "ticket=" + URLEncoder.encode(ticket.getTicket(), "UTF-8") - : "&ticket=" + URLEncoder.encode(ticket.getTicket(), "UTF-8"); - } - - HttpRequest request = HttpRequest.get(uri); - if (proxyInfo != null) { - provider.useProxy(proxyInfo); - } - request.withConnectionProvider(provider); - - HttpResponse response = request.send(); - String contentTypeHeader = response.header("Content-Type"); - if (MimeTypes.MIME_TEXT_PLAIN.equals(contentTypeHeader)) { - String responseContent = response.bodyText(); - throw new WxErrorException(WxError.fromJson(responseContent)); - } - try (InputStream inputStream = new ByteArrayInputStream(response.bodyBytes())) { - return FileUtils.createTmpFile(inputStream, UUID.randomUUID().toString(), "jpg"); - } - } - - @Override - public File executeOkhttp(ConnectionPool pool, final OkhttpProxyInfo proxyInfo, String uri, WxMpQrCodeTicket data) throws WxErrorException, IOException { - OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder().connectionPool(pool); - //设置代理 - if (proxyInfo != null) { - clientBuilder.proxy(proxyInfo.getProxy()); - } - //设置授权 - clientBuilder.authenticator(new Authenticator() { - @Override - public Request authenticate(Route route, Response response) throws IOException { - String credential = Credentials.basic(proxyInfo.getProxyUsername(), proxyInfo.getProxyPassword()); - return response.request().newBuilder() - .header("Authorization", credential) - .build(); - } - }); - //得到httpClient - OkHttpClient client = clientBuilder.build(); - - Request request = new Request.Builder().url(uri).get().build(); - Response response = client.newCall(request).execute(); - String contentTypeHeader = response.header("Content-Type"); - if (MimeTypes.MIME_TEXT_PLAIN.equals(contentTypeHeader)) { - String responseContent = response.body().string(); - throw new WxErrorException(WxError.fromJson(responseContent)); - } - try (InputStream inputStream = new ByteArrayInputStream(response.body().bytes())) { - return FileUtils.createTmpFile(inputStream, UUID.randomUUID().toString(), "jpg"); - } + public QrCodeRequestExecutor(RequestHttp requestHttp){ + this.requestHttp =requestHttp; } - @Override - public File executeApache(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, - WxMpQrCodeTicket ticket) throws WxErrorException, IOException { - - if (ticket != null) { - if (uri.indexOf('?') == -1) { - uri += '?'; - } - uri += uri.endsWith("?") - ? "ticket=" + URLEncoder.encode(ticket.getTicket(), "UTF-8") - : "&ticket=" + URLEncoder.encode(ticket.getTicket(), "UTF-8"); - } - - HttpGet httpGet = new HttpGet(uri); - if (httpProxy != null) { - RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build(); - httpGet.setConfig(config); - } - - try (CloseableHttpResponse response = httpclient.execute(httpGet); - InputStream inputStream = InputStreamResponseHandler.INSTANCE.handleResponse(response);) { - Header[] contentTypeHeader = response.getHeaders("Content-Type"); - if (contentTypeHeader != null && contentTypeHeader.length > 0) { - // 出错 - if (ContentType.TEXT_PLAIN.getMimeType().equals(contentTypeHeader[0].getValue())) { - String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); - throw new WxErrorException(WxError.fromJson(responseContent)); - } - } - return FileUtils.createTmpFile(inputStream, UUID.randomUUID().toString(), "jpg"); - } finally { - httpGet.releaseConnection(); + public static RequestExecutor create(RequestHttp requestHttp){ + switch (requestHttp.getRequestType()){ + case apacheHttp: + return new ApacheQrCodeRequestExecutor(requestHttp); + case joddHttp: + return new JoddQrCodeRequestExecutor(requestHttp); + case okHttp: + return new OkhttpQrCodeRequestExecutor(requestHttp); + default: + //TODO 需要优化,最好抛出异常 + return null; } } - } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialDeleteRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialDeleteRequestExecutor.java new file mode 100644 index 00000000..5446483f --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialDeleteRequestExecutor.java @@ -0,0 +1,52 @@ +package me.chanjar.weixin.mp.util.http.apache; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import org.apache.http.HttpHost; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; + +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.RequestHttp; +import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; +import me.chanjar.weixin.common.util.json.WxGsonBuilder; +import me.chanjar.weixin.mp.util.http.MaterialDeleteRequestExecutor; + +/** + * Created by ecoolper on 2017/5/5. + */ +public class ApacheMaterialDeleteRequestExecutor extends MaterialDeleteRequestExecutor { + public ApacheMaterialDeleteRequestExecutor(RequestHttp requestHttp) { + super(requestHttp); + } + + @Override + public Boolean execute(String uri, String materialId) throws WxErrorException, IOException { + HttpPost httpPost = new HttpPost(uri); + if (requestHttp.getRequestHttpProxy() != null) { + RequestConfig config = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).build(); + httpPost.setConfig(config); + } + + Map params = new HashMap<>(); + params.put("media_id", materialId); + httpPost.setEntity(new StringEntity(WxGsonBuilder.create().toJson(params))); + try (CloseableHttpResponse response = requestHttp.getRequestHttpClient().execute(httpPost)) { + String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); + WxError error = WxError.fromJson(responseContent); + if (error.getErrorCode() != 0) { + throw new WxErrorException(error); + } else { + return true; + } + } finally { + httpPost.releaseConnection(); + } + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialNewsInfoRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialNewsInfoRequestExecutor.java new file mode 100644 index 00000000..81fb8019 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialNewsInfoRequestExecutor.java @@ -0,0 +1,54 @@ +package me.chanjar.weixin.mp.util.http.apache; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import org.apache.http.HttpHost; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; + +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.RequestHttp; +import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; +import me.chanjar.weixin.common.util.json.WxGsonBuilder; +import me.chanjar.weixin.mp.bean.material.WxMpMaterialNews; +import me.chanjar.weixin.mp.util.http.MaterialNewsInfoRequestExecutor; +import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; + +/** + * Created by ecoolper on 2017/5/5. + */ +public class ApacheMaterialNewsInfoRequestExecutor extends MaterialNewsInfoRequestExecutor { + public ApacheMaterialNewsInfoRequestExecutor(RequestHttp requestHttp) { + super(requestHttp); + } + + @Override + public WxMpMaterialNews execute(String uri, String materialId) throws WxErrorException, IOException { + HttpPost httpPost = new HttpPost(uri); + if (requestHttp.getRequestHttpProxy() != null) { + RequestConfig config = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).build(); + httpPost.setConfig(config); + } + + Map params = new HashMap<>(); + params.put("media_id", materialId); + httpPost.setEntity(new StringEntity(WxGsonBuilder.create().toJson(params))); + try (CloseableHttpResponse response = requestHttp.getRequestHttpClient().execute(httpPost)) { + String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); + WxError error = WxError.fromJson(responseContent); + if (error.getErrorCode() != 0) { + throw new WxErrorException(error); + } else { + return WxMpGsonBuilder.create().fromJson(responseContent, WxMpMaterialNews.class); + } + } finally { + httpPost.releaseConnection(); + } + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialUploadRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialUploadRequestExecutor.java new file mode 100644 index 00000000..af6ab10a --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialUploadRequestExecutor.java @@ -0,0 +1,75 @@ +package me.chanjar.weixin.mp.util.http.apache; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.Map; + +import org.apache.http.HttpHost; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.mime.HttpMultipartMode; +import org.apache.http.entity.mime.MultipartEntityBuilder; +import org.apache.http.impl.client.CloseableHttpClient; + +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.RequestHttp; +import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; +import me.chanjar.weixin.common.util.json.WxGsonBuilder; +import me.chanjar.weixin.mp.bean.material.WxMpMaterial; +import me.chanjar.weixin.mp.bean.material.WxMpMaterialUploadResult; +import me.chanjar.weixin.mp.util.http.MaterialUploadRequestExecutor; + +/** + * Created by ecoolper on 2017/5/5. + */ +public class ApacheMaterialUploadRequestExecutor extends MaterialUploadRequestExecutor { + public ApacheMaterialUploadRequestExecutor(RequestHttp requestHttp) { + super(requestHttp); + } + + @Override + public WxMpMaterialUploadResult execute(String uri, WxMpMaterial material) throws WxErrorException, IOException { + HttpPost httpPost = new HttpPost(uri); + if (requestHttp.getRequestHttpProxy() != null) { + RequestConfig response = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).build(); + httpPost.setConfig(response); + } + + if (material == null) { + throw new WxErrorException(WxError.newBuilder().setErrorMsg("非法请求,material参数为空").build()); + } + + File file = material.getFile(); + if (file == null || !file.exists()) { + throw new FileNotFoundException(); + } + + MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); + multipartEntityBuilder + .addBinaryBody("media", file) + .setMode(HttpMultipartMode.RFC6532); + Map form = material.getForm(); + if (material.getForm() != null) { + multipartEntityBuilder.addTextBody("description", WxGsonBuilder.create().toJson(form)); + } + + httpPost.setEntity(multipartEntityBuilder.build()); + httpPost.setHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString()); + + try (CloseableHttpResponse response = requestHttp.getRequestHttpClient().execute(httpPost)) { + String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); + WxError error = WxError.fromJson(responseContent); + if (error.getErrorCode() != 0) { + throw new WxErrorException(error); + } else { + return WxMpMaterialUploadResult.fromJson(responseContent); + } + } finally { + httpPost.releaseConnection(); + } + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialVideoInfoRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialVideoInfoRequestExecutor.java new file mode 100644 index 00000000..1d1e2c57 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialVideoInfoRequestExecutor.java @@ -0,0 +1,53 @@ +package me.chanjar.weixin.mp.util.http.apache; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import org.apache.http.HttpHost; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; + +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.RequestHttp; +import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; +import me.chanjar.weixin.common.util.json.WxGsonBuilder; +import me.chanjar.weixin.mp.bean.material.WxMpMaterialVideoInfoResult; +import me.chanjar.weixin.mp.util.http.MaterialVideoInfoRequestExecutor; + +/** + * Created by ecoolper on 2017/5/5. + */ +public class ApacheMaterialVideoInfoRequestExecutor extends MaterialVideoInfoRequestExecutor { + public ApacheMaterialVideoInfoRequestExecutor(RequestHttp requestHttp) { + super(requestHttp); + } + + @Override + public WxMpMaterialVideoInfoResult execute(String uri, String materialId) throws WxErrorException, IOException { + HttpPost httpPost = new HttpPost(uri); + if (requestHttp.getRequestHttpProxy() != null) { + RequestConfig config = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).build(); + httpPost.setConfig(config); + } + + Map params = new HashMap<>(); + params.put("media_id", materialId); + httpPost.setEntity(new StringEntity(WxGsonBuilder.create().toJson(params))); + try (CloseableHttpResponse response = requestHttp.getRequestHttpClient().execute(httpPost)) { + String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); + WxError error = WxError.fromJson(responseContent); + if (error.getErrorCode() != 0) { + throw new WxErrorException(error); + } else { + return WxMpMaterialVideoInfoResult.fromJson(responseContent); + } + } finally { + httpPost.releaseConnection(); + } + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialVoiceAndImageDownloadRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialVoiceAndImageDownloadRequestExecutor.java new file mode 100644 index 00000000..92cf1c5a --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialVoiceAndImageDownloadRequestExecutor.java @@ -0,0 +1,64 @@ +package me.chanjar.weixin.mp.util.http.apache; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.io.IOUtils; +import org.apache.http.HttpHost; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; + +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.RequestHttp; +import me.chanjar.weixin.common.util.http.apache.InputStreamResponseHandler; +import me.chanjar.weixin.common.util.json.WxGsonBuilder; +import me.chanjar.weixin.mp.util.http.MaterialVoiceAndImageDownloadRequestExecutor; + +/** + * Created by ecoolper on 2017/5/5. + */ +public class ApacheMaterialVoiceAndImageDownloadRequestExecutor extends MaterialVoiceAndImageDownloadRequestExecutor { + public ApacheMaterialVoiceAndImageDownloadRequestExecutor(RequestHttp requestHttp, File tmpDirFile) { + super(requestHttp, tmpDirFile); + } + + @Override + public InputStream execute(String uri, String materialId) throws WxErrorException, IOException { + HttpPost httpPost = new HttpPost(uri); + if (requestHttp.getRequestHttpProxy() != null) { + RequestConfig config = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).build(); + httpPost.setConfig(config); + } + + Map params = new HashMap<>(); + params.put("media_id", materialId); + httpPost.setEntity(new StringEntity(WxGsonBuilder.create().toJson(params))); + try (CloseableHttpResponse response = requestHttp.getRequestHttpClient().execute(httpPost); + InputStream inputStream = InputStreamResponseHandler.INSTANCE.handleResponse(response);) { + // 下载媒体文件出错 + byte[] responseContent = IOUtils.toByteArray(inputStream); + String responseContentString = new String(responseContent, "UTF-8"); + if (responseContentString.length() < 100) { + try { + WxError wxError = WxGsonBuilder.create().fromJson(responseContentString, WxError.class); + if (wxError.getErrorCode() != 0) { + throw new WxErrorException(wxError); + } + } catch (com.google.gson.JsonSyntaxException ex) { + return new ByteArrayInputStream(responseContent); + } + } + return new ByteArrayInputStream(responseContent); + } finally { + httpPost.releaseConnection(); + } + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMediaImgUploadRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMediaImgUploadRequestExecutor.java new file mode 100644 index 00000000..4aaf2f12 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMediaImgUploadRequestExecutor.java @@ -0,0 +1,61 @@ +package me.chanjar.weixin.mp.util.http.apache; + +import java.io.File; +import java.io.IOException; + +import org.apache.http.HttpEntity; +import org.apache.http.HttpHost; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.mime.HttpMultipartMode; +import org.apache.http.entity.mime.MultipartEntityBuilder; +import org.apache.http.impl.client.CloseableHttpClient; + +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.RequestHttp; +import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; +import me.chanjar.weixin.mp.bean.material.WxMediaImgUploadResult; +import me.chanjar.weixin.mp.util.http.MediaImgUploadRequestExecutor; + +/** + * Created by ecoolper on 2017/5/5. + */ +public class ApacheMediaImgUploadRequestExecutor extends MediaImgUploadRequestExecutor { + public ApacheMediaImgUploadRequestExecutor(RequestHttp requestHttp) { + super(requestHttp); + } + + @Override + public WxMediaImgUploadResult execute(String uri, File data) throws WxErrorException, IOException { + if (data == null) { + throw new WxErrorException(WxError.newBuilder().setErrorMsg("文件对象为空").build()); + } + + HttpPost httpPost = new HttpPost(uri); + if (requestHttp.getRequestHttpProxy() != null) { + RequestConfig config = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).build(); + httpPost.setConfig(config); + } + + HttpEntity entity = MultipartEntityBuilder + .create() + .addBinaryBody("media", data) + .setMode(HttpMultipartMode.RFC6532) + .build(); + httpPost.setEntity(entity); + httpPost.setHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString()); + + try (CloseableHttpResponse response = requestHttp.getRequestHttpClient().execute(httpPost)) { + String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); + WxError error = WxError.fromJson(responseContent); + if (error.getErrorCode() != 0) { + throw new WxErrorException(error); + } + + return WxMediaImgUploadResult.fromJson(responseContent); + } + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheQrCodeRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheQrCodeRequestExecutor.java new file mode 100644 index 00000000..dd84f293 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheQrCodeRequestExecutor.java @@ -0,0 +1,66 @@ +package me.chanjar.weixin.mp.util.http.apache; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.URLEncoder; +import java.util.UUID; + +import org.apache.http.Header; +import org.apache.http.HttpHost; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.entity.ContentType; +import org.apache.http.impl.client.CloseableHttpClient; + +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.fs.FileUtils; +import me.chanjar.weixin.common.util.http.RequestHttp; +import me.chanjar.weixin.common.util.http.apache.InputStreamResponseHandler; +import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; +import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket; +import me.chanjar.weixin.mp.util.http.QrCodeRequestExecutor; + +/** + * Created by ecoolper on 2017/5/5. + */ +public class ApacheQrCodeRequestExecutor extends QrCodeRequestExecutor { + public ApacheQrCodeRequestExecutor(RequestHttp requestHttp) { + super(requestHttp); + } + + @Override + public File execute(String uri, WxMpQrCodeTicket ticket) throws WxErrorException, IOException { + if (ticket != null) { + if (uri.indexOf('?') == -1) { + uri += '?'; + } + uri += uri.endsWith("?") + ? "ticket=" + URLEncoder.encode(ticket.getTicket(), "UTF-8") + : "&ticket=" + URLEncoder.encode(ticket.getTicket(), "UTF-8"); + } + + HttpGet httpGet = new HttpGet(uri); + if (requestHttp.getRequestHttpProxy() != null) { + RequestConfig config = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).build(); + httpGet.setConfig(config); + } + + try (CloseableHttpResponse response = requestHttp.getRequestHttpClient().execute(httpGet); + InputStream inputStream = InputStreamResponseHandler.INSTANCE.handleResponse(response);) { + Header[] contentTypeHeader = response.getHeaders("Content-Type"); + if (contentTypeHeader != null && contentTypeHeader.length > 0) { + // 出错 + if (ContentType.TEXT_PLAIN.getMimeType().equals(contentTypeHeader[0].getValue())) { + String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); + throw new WxErrorException(WxError.fromJson(responseContent)); + } + } + return FileUtils.createTmpFile(inputStream, UUID.randomUUID().toString(), "jpg"); + } finally { + httpGet.releaseConnection(); + } + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialDeleteRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialDeleteRequestExecutor.java new file mode 100644 index 00000000..082653b2 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialDeleteRequestExecutor.java @@ -0,0 +1,40 @@ +package me.chanjar.weixin.mp.util.http.jodd; + +import java.io.IOException; + +import jodd.http.HttpConnectionProvider; +import jodd.http.HttpRequest; +import jodd.http.HttpResponse; +import jodd.http.ProxyInfo; +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.RequestHttp; +import me.chanjar.weixin.mp.util.http.MaterialDeleteRequestExecutor; + +/** + * Created by ecoolper on 2017/5/5. + */ +public class JoddMaterialDeleteRequestExecutor extends MaterialDeleteRequestExecutor { + public JoddMaterialDeleteRequestExecutor(RequestHttp requestHttp) { + super(requestHttp); + } + + @Override + public Boolean execute(String uri, String materialId) throws WxErrorException, IOException { + HttpRequest request = HttpRequest.post(uri); + if (requestHttp.getRequestHttpProxy() != null) { + requestHttp.getRequestHttpClient().useProxy(requestHttp.getRequestHttpProxy()); + } + request.withConnectionProvider(requestHttp.getRequestHttpClient()); + + request.query("media_id", materialId); + HttpResponse response = request.send(); + String responseContent = response.bodyText(); + WxError error = WxError.fromJson(responseContent); + if (error.getErrorCode() != 0) { + throw new WxErrorException(error); + } else { + return true; + } + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialNewsInfoRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialNewsInfoRequestExecutor.java new file mode 100644 index 00000000..083cfedc --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialNewsInfoRequestExecutor.java @@ -0,0 +1,43 @@ +package me.chanjar.weixin.mp.util.http.jodd; + +import java.io.IOException; + +import jodd.http.HttpConnectionProvider; +import jodd.http.HttpRequest; +import jodd.http.HttpResponse; +import jodd.http.ProxyInfo; +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.RequestHttp; +import me.chanjar.weixin.mp.bean.material.WxMpMaterialNews; +import me.chanjar.weixin.mp.util.http.MaterialNewsInfoRequestExecutor; +import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; + +/** + * Created by ecoolper on 2017/5/5. + */ +public class JoddMaterialNewsInfoRequestExecutor extends MaterialNewsInfoRequestExecutor { + public JoddMaterialNewsInfoRequestExecutor(RequestHttp requestHttp) { + super(requestHttp); + } + + @Override + public WxMpMaterialNews execute(String uri, String materialId) throws WxErrorException, IOException { + HttpRequest request = HttpRequest.post(uri); + if (requestHttp.getRequestHttpProxy() != null) { + requestHttp.getRequestHttpClient().useProxy(requestHttp.getRequestHttpProxy()); + } + request.withConnectionProvider(requestHttp.getRequestHttpClient()); + + request.query("media_id", materialId); + HttpResponse response = request.send(); + + String responseContent = response.bodyText(); + WxError error = WxError.fromJson(responseContent); + if (error.getErrorCode() != 0) { + throw new WxErrorException(error); + } else { + return WxMpGsonBuilder.create().fromJson(responseContent, WxMpMaterialNews.class); + } + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialUploadRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialUploadRequestExecutor.java new file mode 100644 index 00000000..4c1fe480 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialUploadRequestExecutor.java @@ -0,0 +1,59 @@ +package me.chanjar.weixin.mp.util.http.jodd; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.Map; + +import jodd.http.HttpConnectionProvider; +import jodd.http.HttpRequest; +import jodd.http.HttpResponse; +import jodd.http.ProxyInfo; +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.RequestHttp; +import me.chanjar.weixin.common.util.json.WxGsonBuilder; +import me.chanjar.weixin.mp.bean.material.WxMpMaterial; +import me.chanjar.weixin.mp.bean.material.WxMpMaterialUploadResult; +import me.chanjar.weixin.mp.util.http.MaterialUploadRequestExecutor; + +/** + * Created by ecoolper on 2017/5/5. + */ +public class JoddMaterialUploadRequestExecutor extends MaterialUploadRequestExecutor { + public JoddMaterialUploadRequestExecutor(RequestHttp requestHttp) { + super(requestHttp); + } + + @Override + public WxMpMaterialUploadResult execute(String uri, WxMpMaterial material) throws WxErrorException, IOException { + HttpRequest request = HttpRequest.post(uri); + if (requestHttp.getRequestHttpProxy() != null) { + requestHttp.getRequestHttpClient().useProxy(requestHttp.getRequestHttpProxy()); + } + request.withConnectionProvider(requestHttp.getRequestHttpClient()); + + if (material == null) { + throw new WxErrorException(WxError.newBuilder().setErrorMsg("非法请求,material参数为空").build()); + } + + File file = material.getFile(); + if (file == null || !file.exists()) { + throw new FileNotFoundException(); + } + request.form("media", file); + Map form = material.getForm(); + if (material.getForm() != null) { + request.form("description", WxGsonBuilder.create().toJson(form)); + } + + HttpResponse response = request.send(); + String responseContent = response.bodyText(); + WxError error = WxError.fromJson(responseContent); + if (error.getErrorCode() != 0) { + throw new WxErrorException(error); + } else { + return WxMpMaterialUploadResult.fromJson(responseContent); + } + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialVideoInfoRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialVideoInfoRequestExecutor.java new file mode 100644 index 00000000..ed7bfc04 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialVideoInfoRequestExecutor.java @@ -0,0 +1,41 @@ +package me.chanjar.weixin.mp.util.http.jodd; + +import java.io.IOException; + +import jodd.http.HttpConnectionProvider; +import jodd.http.HttpRequest; +import jodd.http.HttpResponse; +import jodd.http.ProxyInfo; +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.RequestHttp; +import me.chanjar.weixin.mp.bean.material.WxMpMaterialVideoInfoResult; +import me.chanjar.weixin.mp.util.http.MaterialVideoInfoRequestExecutor; + +/** + * Created by ecoolper on 2017/5/5. + */ +public class JoddMaterialVideoInfoRequestExecutor extends MaterialVideoInfoRequestExecutor { + public JoddMaterialVideoInfoRequestExecutor(RequestHttp requestHttp) { + super(requestHttp); + } + + @Override + public WxMpMaterialVideoInfoResult execute(String uri, String materialId) throws WxErrorException, IOException { + HttpRequest request = HttpRequest.post(uri); + if (requestHttp.getRequestHttpProxy() != null) { + requestHttp.getRequestHttpClient().useProxy(requestHttp.getRequestHttpProxy()); + } + request.withConnectionProvider(requestHttp.getRequestHttpClient()); + + request.query("media_id", materialId); + HttpResponse response = request.send(); + String responseContent = response.bodyText(); + WxError error = WxError.fromJson(responseContent); + if (error.getErrorCode() != 0) { + throw new WxErrorException(error); + } else { + return WxMpMaterialVideoInfoResult.fromJson(responseContent); + } + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialVoiceAndImageDownloadRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialVoiceAndImageDownloadRequestExecutor.java new file mode 100644 index 00000000..b8da949e --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialVoiceAndImageDownloadRequestExecutor.java @@ -0,0 +1,56 @@ +package me.chanjar.weixin.mp.util.http.jodd; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; + +import org.apache.commons.io.IOUtils; + +import jodd.http.HttpConnectionProvider; +import jodd.http.HttpRequest; +import jodd.http.HttpResponse; +import jodd.http.ProxyInfo; +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.RequestHttp; +import me.chanjar.weixin.common.util.json.WxGsonBuilder; +import me.chanjar.weixin.mp.util.http.MaterialVoiceAndImageDownloadRequestExecutor; +import me.chanjar.weixin.mp.util.http.okhttp.OkhttpMaterialVoiceAndImageDownloadRequestExecutor; + +/** + * Created by ecoolper on 2017/5/5. + */ +public class JoddMaterialVoiceAndImageDownloadRequestExecutor extends MaterialVoiceAndImageDownloadRequestExecutor { + public JoddMaterialVoiceAndImageDownloadRequestExecutor(RequestHttp requestHttp, File tmpDirFile) { + super(requestHttp, tmpDirFile); + } + + @Override + public InputStream execute(String uri, String materialId) throws WxErrorException, IOException { + HttpRequest request = HttpRequest.post(uri); + if (requestHttp.getRequestHttpProxy() != null) { + requestHttp.getRequestHttpClient().useProxy(requestHttp.getRequestHttpProxy()); + } + request.withConnectionProvider(requestHttp.getRequestHttpClient()); + + request.query("media_id", materialId); + HttpResponse response = request.send(); + try (InputStream inputStream = new ByteArrayInputStream(response.bodyBytes())) { + // 下载媒体文件出错 + byte[] responseContent = IOUtils.toByteArray(inputStream); + String responseContentString = new String(responseContent, "UTF-8"); + if (responseContentString.length() < 100) { + try { + WxError wxError = WxGsonBuilder.create().fromJson(responseContentString, WxError.class); + if (wxError.getErrorCode() != 0) { + throw new WxErrorException(wxError); + } + } catch (com.google.gson.JsonSyntaxException ex) { + return new ByteArrayInputStream(responseContent); + } + } + return new ByteArrayInputStream(responseContent); + } + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMediaImgUploadRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMediaImgUploadRequestExecutor.java new file mode 100644 index 00000000..82bfbf81 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMediaImgUploadRequestExecutor.java @@ -0,0 +1,46 @@ +package me.chanjar.weixin.mp.util.http.jodd; + +import java.io.File; +import java.io.IOException; + +import jodd.http.HttpConnectionProvider; +import jodd.http.HttpRequest; +import jodd.http.HttpResponse; +import jodd.http.ProxyInfo; +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.RequestHttp; +import me.chanjar.weixin.mp.bean.material.WxMediaImgUploadResult; +import me.chanjar.weixin.mp.util.http.MediaImgUploadRequestExecutor; + +/** + * Created by ecoolper on 2017/5/5. + */ +public class JoddMediaImgUploadRequestExecutor extends MediaImgUploadRequestExecutor { + public JoddMediaImgUploadRequestExecutor(RequestHttp requestHttp) { + super(requestHttp); + } + + @Override + public WxMediaImgUploadResult execute(String uri, File data) throws WxErrorException, IOException { + if (data == null) { + throw new WxErrorException(WxError.newBuilder().setErrorMsg("文件对象为空").build()); + } + + HttpRequest request = HttpRequest.post(uri); + if (requestHttp.getRequestHttpProxy() != null) { + requestHttp.getRequestHttpClient().useProxy(requestHttp.getRequestHttpProxy()); + } + request.withConnectionProvider(requestHttp.getRequestHttpClient()); + + request.form("media", data); + HttpResponse response = request.send(); + String responseContent = response.bodyText(); + WxError error = WxError.fromJson(responseContent); + if (error.getErrorCode() != 0) { + throw new WxErrorException(error); + } + + return WxMediaImgUploadResult.fromJson(responseContent); + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddQrCodeRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddQrCodeRequestExecutor.java new file mode 100644 index 00000000..1191751c --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddQrCodeRequestExecutor.java @@ -0,0 +1,57 @@ +package me.chanjar.weixin.mp.util.http.jodd; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.URLEncoder; +import java.util.UUID; + +import jodd.http.HttpConnectionProvider; +import jodd.http.HttpRequest; +import jodd.http.HttpResponse; +import jodd.http.ProxyInfo; +import jodd.util.MimeTypes; +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.fs.FileUtils; +import me.chanjar.weixin.common.util.http.RequestHttp; +import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket; +import me.chanjar.weixin.mp.util.http.QrCodeRequestExecutor; + +/** + * Created by ecoolper on 2017/5/5. + */ +public class JoddQrCodeRequestExecutor extends QrCodeRequestExecutor { + public JoddQrCodeRequestExecutor(RequestHttp requestHttp) { + super(requestHttp); + } + + @Override + public File execute(String uri, WxMpQrCodeTicket ticket) throws WxErrorException, IOException { + if (ticket != null) { + if (uri.indexOf('?') == -1) { + uri += '?'; + } + uri += uri.endsWith("?") + ? "ticket=" + URLEncoder.encode(ticket.getTicket(), "UTF-8") + : "&ticket=" + URLEncoder.encode(ticket.getTicket(), "UTF-8"); + } + + HttpRequest request = HttpRequest.get(uri); + if (requestHttp.getRequestHttpProxy() != null) { + requestHttp.getRequestHttpClient().useProxy(requestHttp.getRequestHttpProxy()); + } + request.withConnectionProvider(requestHttp.getRequestHttpClient()); + + HttpResponse response = request.send(); + String contentTypeHeader = response.header("Content-Type"); + if (MimeTypes.MIME_TEXT_PLAIN.equals(contentTypeHeader)) { + String responseContent = response.bodyText(); + throw new WxErrorException(WxError.fromJson(responseContent)); + } + try (InputStream inputStream = new ByteArrayInputStream(response.bodyBytes())) { + return FileUtils.createTmpFile(inputStream, UUID.randomUUID().toString(), "jpg"); + } + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialDeleteRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialDeleteRequestExecutor.java new file mode 100644 index 00000000..5da55877 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialDeleteRequestExecutor.java @@ -0,0 +1,54 @@ +package me.chanjar.weixin.mp.util.http.okhttp; + +import java.io.IOException; + +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.RequestExecutor; +import me.chanjar.weixin.common.util.http.RequestHttp; +import me.chanjar.weixin.common.util.http.okhttp.OkhttpProxyInfo; +import me.chanjar.weixin.mp.util.http.MaterialDeleteRequestExecutor; +import okhttp3.*; + +/** + * Created by ecoolper on 2017/5/5. + */ +public class OkhttpMaterialDeleteRequestExecutor extends MaterialDeleteRequestExecutor { + + + public OkhttpMaterialDeleteRequestExecutor(RequestHttp requestHttp) { + super(requestHttp); + } + + @Override + public Boolean execute(String uri, String materialId) throws WxErrorException, IOException { + OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder().connectionPool(requestHttp.getRequestHttpClient()); + //设置代理 + if (requestHttp.getRequestHttpProxy() != null) { + clientBuilder.proxy(requestHttp.getRequestHttpProxy().getProxy()); + } + //设置授权 + clientBuilder.authenticator(new Authenticator() { + @Override + public Request authenticate(Route route, Response response) throws IOException { + String credential = Credentials.basic(requestHttp.getRequestHttpProxy().getProxyUsername(), requestHttp.getRequestHttpProxy().getProxyPassword()); + return response.request().newBuilder() + .header("Authorization", credential) + .build(); + } + }); + //得到httpClient + OkHttpClient client = clientBuilder.build(); + + RequestBody requestBody = new FormBody.Builder().add("media_id", materialId).build(); + Request request = new Request.Builder().url(uri).post(requestBody).build(); + Response response = client.newCall(request).execute(); + String responseContent = response.body().string(); + WxError error = WxError.fromJson(responseContent); + if (error.getErrorCode() != 0) { + throw new WxErrorException(error); + } else { + return true; + } + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialNewsInfoRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialNewsInfoRequestExecutor.java new file mode 100644 index 00000000..c7efbb89 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialNewsInfoRequestExecutor.java @@ -0,0 +1,55 @@ +package me.chanjar.weixin.mp.util.http.okhttp; + +import java.io.IOException; + +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.RequestHttp; +import me.chanjar.weixin.common.util.http.okhttp.OkhttpProxyInfo; +import me.chanjar.weixin.mp.bean.material.WxMpMaterialNews; +import me.chanjar.weixin.mp.util.http.MaterialNewsInfoRequestExecutor; +import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; +import okhttp3.*; + +/** + * Created by ecoolper on 2017/5/5. + */ +public class OkhttpMaterialNewsInfoRequestExecutor extends MaterialNewsInfoRequestExecutor { + public OkhttpMaterialNewsInfoRequestExecutor(RequestHttp requestHttp) { + super(requestHttp); + } + + @Override + public WxMpMaterialNews execute(String uri, String materialId) throws WxErrorException, IOException { + OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder().connectionPool(requestHttp.getRequestHttpClient()); + //设置代理 + if (requestHttp.getRequestHttpProxy() != null) { + clientBuilder.proxy(requestHttp.getRequestHttpProxy().getProxy()); + } + //设置授权 + clientBuilder.authenticator(new Authenticator() { + @Override + public Request authenticate(Route route, Response response) throws IOException { + String credential = Credentials.basic(requestHttp.getRequestHttpProxy().getProxyUsername(), requestHttp.getRequestHttpProxy().getProxyPassword()); + return response.request().newBuilder() + .header("Authorization", credential) + .build(); + } + }); + //得到httpClient + OkHttpClient client = clientBuilder.build(); + + RequestBody requestBody = new FormBody.Builder().add("media_id", materialId).build(); + Request request = new Request.Builder().url(uri).post(requestBody).build(); + + Response response = client.newCall(request).execute(); + String responseContent = response.body().string(); + + WxError error = WxError.fromJson(responseContent); + if (error.getErrorCode() != 0) { + throw new WxErrorException(error); + } else { + return WxMpGsonBuilder.create().fromJson(responseContent, WxMpMaterialNews.class); + } + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialUploadRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialUploadRequestExecutor.java new file mode 100644 index 00000000..4be74cda --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialUploadRequestExecutor.java @@ -0,0 +1,80 @@ +package me.chanjar.weixin.mp.util.http.okhttp; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.Map; + +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.mime.HttpMultipartMode; +import org.apache.http.entity.mime.MultipartEntityBuilder; + +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.RequestHttp; +import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; +import me.chanjar.weixin.common.util.http.okhttp.OkhttpProxyInfo; +import me.chanjar.weixin.common.util.json.WxGsonBuilder; +import me.chanjar.weixin.mp.bean.material.WxMpMaterial; +import me.chanjar.weixin.mp.bean.material.WxMpMaterialUploadResult; +import me.chanjar.weixin.mp.util.http.MaterialUploadRequestExecutor; +import okhttp3.*; + +/** + * Created by ecoolper on 2017/5/5. + */ +public class OkhttpMaterialUploadRequestExecutor extends MaterialUploadRequestExecutor { + public OkhttpMaterialUploadRequestExecutor(RequestHttp requestHttp) { + super(requestHttp); + } + + @Override + public WxMpMaterialUploadResult execute(String uri, WxMpMaterial material) throws WxErrorException, IOException { + OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder().connectionPool(requestHttp.getRequestHttpClient()); + //设置代理 + if (requestHttp.getRequestHttpProxy() != null) { + clientBuilder.proxy(requestHttp.getRequestHttpProxy().getProxy()); + } + //设置授权 + clientBuilder.authenticator(new Authenticator() { + @Override + public Request authenticate(Route route, Response response) throws IOException { + String credential = Credentials.basic(requestHttp.getRequestHttpProxy().getProxyUsername(), requestHttp.getRequestHttpProxy().getProxyPassword()); + return response.request().newBuilder() + .header("Authorization", credential) + .build(); + } + }); + //得到httpClient + OkHttpClient client = clientBuilder.build(); + + + if (material == null) { + throw new WxErrorException(WxError.newBuilder().setErrorMsg("非法请求,material参数为空").build()); + } + + File file = material.getFile(); + if (file == null || !file.exists()) { + throw new FileNotFoundException(); + } + RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), file); + MultipartBody.Builder bodyBuilder = new MultipartBody.Builder().addFormDataPart("media", null, fileBody); + Map form = material.getForm(); + if (material.getForm() != null) { + bodyBuilder.addFormDataPart("description", WxGsonBuilder.create().toJson(form)); + } + RequestBody body =bodyBuilder.build(); + Request request = new Request.Builder().url(uri).post(body).build(); + Response response = client.newCall(request).execute(); + String responseContent = response.body().string(); + WxError error = WxError.fromJson(responseContent); + if (error.getErrorCode() != 0) { + throw new WxErrorException(error); + } else { + return WxMpMaterialUploadResult.fromJson(responseContent); + } + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialVideoInfoRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialVideoInfoRequestExecutor.java new file mode 100644 index 00000000..c431d70a --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialVideoInfoRequestExecutor.java @@ -0,0 +1,52 @@ +package me.chanjar.weixin.mp.util.http.okhttp; + +import java.io.IOException; + +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.RequestHttp; +import me.chanjar.weixin.common.util.http.okhttp.OkhttpProxyInfo; +import me.chanjar.weixin.mp.bean.material.WxMpMaterialVideoInfoResult; +import me.chanjar.weixin.mp.util.http.MaterialVideoInfoRequestExecutor; +import okhttp3.*; + +/** + * Created by ecoolper on 2017/5/5. + */ +public class OkhttpMaterialVideoInfoRequestExecutor extends MaterialVideoInfoRequestExecutor { + public OkhttpMaterialVideoInfoRequestExecutor(RequestHttp requestHttp) { + super(requestHttp); + } + + @Override + public WxMpMaterialVideoInfoResult execute(String uri, String materialId) throws WxErrorException, IOException { + OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder().connectionPool(requestHttp.getRequestHttpClient()); + //设置代理 + if (requestHttp.getRequestHttpProxy() != null) { + clientBuilder.proxy(requestHttp.getRequestHttpProxy().getProxy()); + } + //设置授权 + clientBuilder.authenticator(new Authenticator() { + @Override + public Request authenticate(Route route, Response response) throws IOException { + String credential = Credentials.basic(requestHttp.getRequestHttpProxy().getProxyUsername(), requestHttp.getRequestHttpProxy().getProxyPassword()); + return response.request().newBuilder() + .header("Authorization", credential) + .build(); + } + }); + //得到httpClient + OkHttpClient client = clientBuilder.build(); + + RequestBody requestBody =new FormBody.Builder().add("media_id", materialId).build(); + Request request = new Request.Builder().url(uri).post(requestBody).build(); + Response response = client.newCall(request).execute(); + String responseContent = response.body().string(); + WxError error = WxError.fromJson(responseContent); + if (error.getErrorCode() != 0) { + throw new WxErrorException(error); + } else { + return WxMpMaterialVideoInfoResult.fromJson(responseContent); + } + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialVoiceAndImageDownloadRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialVoiceAndImageDownloadRequestExecutor.java new file mode 100644 index 00000000..3cd1eb98 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialVoiceAndImageDownloadRequestExecutor.java @@ -0,0 +1,68 @@ +package me.chanjar.weixin.mp.util.http.okhttp; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; + +import org.apache.commons.io.IOUtils; + +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.RequestHttp; +import me.chanjar.weixin.common.util.http.okhttp.OkhttpProxyInfo; +import me.chanjar.weixin.common.util.json.WxGsonBuilder; +import me.chanjar.weixin.mp.util.http.MaterialVoiceAndImageDownloadRequestExecutor; +import okhttp3.*; + +/** + * Created by ecoolper on 2017/5/5. + */ +public class OkhttpMaterialVoiceAndImageDownloadRequestExecutor extends MaterialVoiceAndImageDownloadRequestExecutor { + public OkhttpMaterialVoiceAndImageDownloadRequestExecutor(RequestHttp requestHttp, File tmpDirFile) { + super(requestHttp, tmpDirFile); + } + + @Override + public InputStream execute(String uri, String materialId) throws WxErrorException, IOException { + OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder().connectionPool(requestHttp.getRequestHttpClient()); + //设置代理 + if (requestHttp.getRequestHttpProxy() != null) { + clientBuilder.proxy(requestHttp.getRequestHttpProxy().getProxy()); + } + //设置授权 + clientBuilder.authenticator(new Authenticator() { + @Override + public Request authenticate(Route route, Response response) throws IOException { + String credential = Credentials.basic(requestHttp.getRequestHttpProxy().getProxyUsername(), requestHttp.getRequestHttpProxy().getProxyPassword()); + return response.request().newBuilder() + .header("Authorization", credential) + .build(); + } + }); + //得到httpClient + OkHttpClient client = clientBuilder.build(); + + RequestBody requestBody = new FormBody.Builder().add("media_id", materialId).build(); + Request request = new Request.Builder().url(uri).get().post(requestBody).build(); + Response response = client.newCall(request).execute(); + + try (InputStream inputStream = new ByteArrayInputStream(response.body().bytes())) { + + // 下载媒体文件出错 + byte[] responseContent = IOUtils.toByteArray(inputStream); + String responseContentString = new String(responseContent, "UTF-8"); + if (responseContentString.length() < 100) { + try { + WxError wxError = WxGsonBuilder.create().fromJson(responseContentString, WxError.class); + if (wxError.getErrorCode() != 0) { + throw new WxErrorException(wxError); + } + } catch (com.google.gson.JsonSyntaxException ex) { + return new ByteArrayInputStream(responseContent); + } + } + return new ByteArrayInputStream(responseContent); + } + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMediaImgUploadRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMediaImgUploadRequestExecutor.java new file mode 100644 index 00000000..790dd17e --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMediaImgUploadRequestExecutor.java @@ -0,0 +1,56 @@ +package me.chanjar.weixin.mp.util.http.okhttp; + +import java.io.File; +import java.io.IOException; + +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.RequestHttp; +import me.chanjar.weixin.common.util.http.okhttp.OkhttpProxyInfo; +import me.chanjar.weixin.mp.bean.material.WxMediaImgUploadResult; +import me.chanjar.weixin.mp.util.http.MediaImgUploadRequestExecutor; +import okhttp3.*; + +/** + * Created by ecoolper on 2017/5/5. + */ +public class OkhttpMediaImgUploadRequestExecutor extends MediaImgUploadRequestExecutor { + + public OkhttpMediaImgUploadRequestExecutor(RequestHttp requestHttp) { + super(requestHttp); + } + + @Override + public WxMediaImgUploadResult execute(String uri, File data) throws WxErrorException, IOException { + OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder().connectionPool(requestHttp.getRequestHttpClient()); + //设置代理 + if (requestHttp.getRequestHttpProxy() != null) { + clientBuilder.proxy(requestHttp.getRequestHttpProxy().getProxy()); + } + //设置授权 + clientBuilder.authenticator(new Authenticator() { + @Override + public Request authenticate(Route route, Response response) throws IOException { + String credential = Credentials.basic(requestHttp.getRequestHttpProxy().getProxyUsername(), requestHttp.getRequestHttpProxy().getProxyPassword()); + return response.request().newBuilder() + .header("Authorization", credential) + .build(); + } + }); + //得到httpClient + OkHttpClient client = clientBuilder.build(); + + RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), data); + RequestBody body = new MultipartBody.Builder().addFormDataPart("media", null, fileBody).build(); + Request request = new Request.Builder().url(uri).post(body).build(); + + Response response = client.newCall(request).execute(); + String responseContent = response.body().string(); + WxError error = WxError.fromJson(responseContent); + if (error.getErrorCode() != 0) { + throw new WxErrorException(error); + } + + return WxMediaImgUploadResult.fromJson(responseContent); + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpQrCodeRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpQrCodeRequestExecutor.java new file mode 100644 index 00000000..b2cb372f --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpQrCodeRequestExecutor.java @@ -0,0 +1,58 @@ +package me.chanjar.weixin.mp.util.http.okhttp; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.UUID; + +import jodd.util.MimeTypes; +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.fs.FileUtils; +import me.chanjar.weixin.common.util.http.RequestHttp; +import me.chanjar.weixin.common.util.http.okhttp.OkhttpProxyInfo; +import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket; +import me.chanjar.weixin.mp.util.http.QrCodeRequestExecutor; +import okhttp3.*; + +/** + * Created by ecoolper on 2017/5/5. + */ +public class OkhttpQrCodeRequestExecutor extends QrCodeRequestExecutor { + public OkhttpQrCodeRequestExecutor(RequestHttp requestHttp) { + super(requestHttp); + } + + @Override + public File execute(String uri, WxMpQrCodeTicket data) throws WxErrorException, IOException { + OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder().connectionPool(requestHttp.getRequestHttpClient()); + //设置代理 + if (requestHttp.getRequestHttpProxy() != null) { + clientBuilder.proxy(requestHttp.getRequestHttpProxy().getProxy()); + } + //设置授权 + clientBuilder.authenticator(new Authenticator() { + @Override + public Request authenticate(Route route, Response response) throws IOException { + String credential = Credentials.basic(requestHttp.getRequestHttpProxy().getProxyUsername(), requestHttp.getRequestHttpProxy().getProxyPassword()); + return response.request().newBuilder() + .header("Authorization", credential) + .build(); + } + }); + //得到httpClient + OkHttpClient client = clientBuilder.build(); + + Request request = new Request.Builder().url(uri).get().build(); + Response response = client.newCall(request).execute(); + String contentTypeHeader = response.header("Content-Type"); + if (MimeTypes.MIME_TEXT_PLAIN.equals(contentTypeHeader)) { + String responseContent = response.body().string(); + throw new WxErrorException(WxError.fromJson(responseContent)); + } + try (InputStream inputStream = new ByteArrayInputStream(response.body().bytes())) { + return FileUtils.createTmpFile(inputStream, UUID.randomUUID().toString(), "jpg"); + } + } +} From 5234459733e3e8de836b992c6b11952fbd503f14 Mon Sep 17 00:00:00 2001 From: Binary Wang Date: Tue, 9 May 2017 15:26:52 +0800 Subject: [PATCH 02/13] =?UTF-8?q?WxMpXmlMessage=E4=B8=AD=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E5=BE=AE=E4=BF=A1=E6=8E=A8=E9=80=81=E7=94=A8=E6=88=B7=E6=A0=B8?= =?UTF-8?q?=E9=94=80=E5=8D=A1=E5=88=B8=E4=BA=8B=E4=BB=B6=E6=97=B6=E6=89=80?= =?UTF-8?q?=E9=9C=80=E7=9A=84=E5=87=A0=E4=B8=AA=E5=B1=9E=E6=80=A7=20#213?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mp/bean/message/WxMpXmlMessage.java | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/message/WxMpXmlMessage.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/message/WxMpXmlMessage.java index e8802842..fd5a1725 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/message/WxMpXmlMessage.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/message/WxMpXmlMessage.java @@ -204,7 +204,10 @@ public class WxMpXmlMessage implements Serializable { private String isRestoreMemberCard; /** + *
    * 领取场景值,用于领取渠道数据统计。可在生成二维码接口及添加Addcard接口中自定义该字段的字符串值。
+   * 核销卡券时:开发者发起核销时传入的自定义参数,用于进行核销渠道统计
+   * 
*/ @XStreamAlias("OuterStr") private String outerStr; @@ -221,6 +224,36 @@ public class WxMpXmlMessage implements Serializable { @XStreamAlias("IsChatRoom") private String isChatRoom; + /** + * 核销来源。支持开发者统计API核销(FROM_API)、公众平台核销(FROM_MP)、卡券商户助手核销(FROM_MOBILE_HELPER)(核销员微信号) + */ + @XStreamAlias("ConsumeSource") + private String consumeSource; + + /** + * 门店名称,当前卡券核销的门店名称(只有通过自助核销和买单核销时才会出现该字段) + */ + @XStreamAlias("LocationName") + private String locationName; + + /** + * 核销该卡券核销员的openid(只有通过卡券商户助手核销时才会出现) + */ + @XStreamAlias("StaffOpenId") + private String staffOpenId; + + /** + * 自助核销时,用户输入的验证码 + */ + @XStreamAlias("VerifyCode") + private String verifyCode; + + /** + * 自助核销时,用户输入的备注金额 + */ + @XStreamAlias("RemarkAmount") + private String remarkAmount; + @XStreamAlias("ScanCodeInfo") private ScanCodeInfo scanCodeInfo = new ScanCodeInfo(); @@ -861,6 +894,46 @@ public class WxMpXmlMessage implements Serializable { this.isChatRoom = isChatRoom; } + public String getConsumeSource() { + return this.consumeSource; + } + + public void setConsumeSource(String consumeSource) { + this.consumeSource = consumeSource; + } + + public String getLocationName() { + return this.locationName; + } + + public void setLocationName(String locationName) { + this.locationName = locationName; + } + + public String getStaffOpenId() { + return this.staffOpenId; + } + + public void setStaffOpenId(String staffOpenId) { + this.staffOpenId = staffOpenId; + } + + public String getVerifyCode() { + return this.verifyCode; + } + + public void setVerifyCode(String verifyCode) { + this.verifyCode = verifyCode; + } + + public String getRemarkAmount() { + return this.remarkAmount; + } + + public void setRemarkAmount(String remarkAmount) { + this.remarkAmount = remarkAmount; + } + @Override public String toString() { return ToStringUtils.toSimpleString(this); From ae4cbf98b8f811318bd8030d46cd15968e79c9f8 Mon Sep 17 00:00:00 2001 From: Andy Huo Date: Wed, 10 May 2017 11:23:03 +0800 Subject: [PATCH 03/13] =?UTF-8?q?=E6=B7=BB=E5=8A=A0DNS=E8=A7=A3=E6=9E=90?= =?UTF-8?q?=E5=99=A8=E6=94=AF=E6=8C=81=20(#171)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 支持api.weixin.qq.com域名绑定指定的IP 防止域名对应的IP跳跃,导致防火墙策略失效! --- .../util/http/ApacheHttpDnsClientBuilder.java | 314 ++++++++++++++++++ .../common/util/http/WxDnsResolver.java | 64 ++++ 2 files changed, 378 insertions(+) create mode 100644 weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/ApacheHttpDnsClientBuilder.java create mode 100644 weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/WxDnsResolver.java diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/ApacheHttpDnsClientBuilder.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/ApacheHttpDnsClientBuilder.java new file mode 100644 index 00000000..e98fce64 --- /dev/null +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/ApacheHttpDnsClientBuilder.java @@ -0,0 +1,314 @@ +package me.chanjar.weixin.common.util.http; + +import org.apache.commons.lang3.StringUtils; +import org.apache.http.annotation.NotThreadSafe; +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.CredentialsProvider; +import org.apache.http.client.HttpRequestRetryHandler; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.config.Registry; +import org.apache.http.config.RegistryBuilder; +import org.apache.http.config.SocketConfig; +import org.apache.http.conn.DnsResolver; +import org.apache.http.conn.HttpClientConnectionManager; +import org.apache.http.conn.socket.ConnectionSocketFactory; +import org.apache.http.conn.socket.PlainConnectionSocketFactory; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.impl.client.BasicCredentialsProvider; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.apache.http.protocol.HttpContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * httpclient 连接管理器 自带DNS解析 + * + * 大部分代码拷贝自:DefaultApacheHttpClientBuilder + * + * @author Andy.Huo + */ +@NotThreadSafe +public class ApacheHttpDnsClientBuilder implements ApacheHttpClientBuilder { + protected final Logger log = LoggerFactory.getLogger(ApacheHttpDnsClientBuilder.class); + private final AtomicBoolean prepared = new AtomicBoolean(false); + private int connectionRequestTimeout = 3000; + private int connectionTimeout = 5000; + private int soTimeout = 5000; + private int idleConnTimeout = 60000; + private int checkWaitTime = 60000; + private int maxConnPerHost = 10; + private int maxTotalConn = 50; + private String userAgent; + + private DnsResolver dnsResover; + + private HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() { + @Override + public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { + return false; + } + }; + private SSLConnectionSocketFactory sslConnectionSocketFactory = SSLConnectionSocketFactory.getSocketFactory(); + private PlainConnectionSocketFactory plainConnectionSocketFactory = PlainConnectionSocketFactory.getSocketFactory(); + private String httpProxyHost; + private int httpProxyPort; + private String httpProxyUsername; + private String httpProxyPassword; + + /** + * 闲置连接监控线程 + */ + private IdleConnectionMonitorThread idleConnectionMonitorThread; + private HttpClientBuilder httpClientBuilder; + + private ApacheHttpDnsClientBuilder() { + } + + public static ApacheHttpDnsClientBuilder get() { + return new ApacheHttpDnsClientBuilder(); + } + + @Override + public ApacheHttpClientBuilder httpProxyHost(String httpProxyHost) { + this.httpProxyHost = httpProxyHost; + return this; + } + + @Override + public ApacheHttpClientBuilder httpProxyPort(int httpProxyPort) { + this.httpProxyPort = httpProxyPort; + return this; + } + + @Override + public ApacheHttpClientBuilder httpProxyUsername(String httpProxyUsername) { + this.httpProxyUsername = httpProxyUsername; + return this; + } + + @Override + public ApacheHttpClientBuilder httpProxyPassword(String httpProxyPassword) { + this.httpProxyPassword = httpProxyPassword; + return this; + } + + @Override + public ApacheHttpClientBuilder sslConnectionSocketFactory(SSLConnectionSocketFactory sslConnectionSocketFactory) { + this.sslConnectionSocketFactory = sslConnectionSocketFactory; + return this; + } + + /** + * 获取链接的超时时间设置,默认3000ms + *

+ * 设置为零时不超时,一直等待. 设置为负数是使用系统默认设置(非上述的3000ms的默认值,而是httpclient的默认设置). + *

+ * + * @param connectionRequestTimeout + * 获取链接的超时时间设置(单位毫秒),默认3000ms + */ + public void setConnectionRequestTimeout(int connectionRequestTimeout) { + this.connectionRequestTimeout = connectionRequestTimeout; + } + + /** + * 建立链接的超时时间,默认为5000ms.由于是在链接池获取链接,此设置应该并不起什么作用 + *

+ * 设置为零时不超时,一直等待. 设置为负数是使用系统默认设置(非上述的5000ms的默认值,而是httpclient的默认设置). + *

+ * + * @param connectionTimeout + * 建立链接的超时时间设置(单位毫秒),默认5000ms + */ + public void setConnectionTimeout(int connectionTimeout) { + this.connectionTimeout = connectionTimeout; + } + + /** + * 默认NIO的socket超时设置,默认5000ms. + * + * @param soTimeout + * 默认NIO的socket超时设置,默认5000ms. + * @see java.net.SocketOptions#SO_TIMEOUT + */ + public void setSoTimeout(int soTimeout) { + this.soTimeout = soTimeout; + } + + /** + * 空闲链接的超时时间,默认60000ms. + *

+ * 超时的链接将在下一次空闲链接检查是被销毁 + *

+ * + * @param idleConnTimeout + * 空闲链接的超时时间,默认60000ms. + */ + public void setIdleConnTimeout(int idleConnTimeout) { + this.idleConnTimeout = idleConnTimeout; + } + + /** + * 检查空间链接的间隔周期,默认60000ms. + * + * @param checkWaitTime + * 检查空间链接的间隔周期,默认60000ms. + */ + public void setCheckWaitTime(int checkWaitTime) { + this.checkWaitTime = checkWaitTime; + } + + /** + * 每路的最大链接数,默认10 + * + * @param maxConnPerHost + * 每路的最大链接数,默认10 + */ + public void setMaxConnPerHost(int maxConnPerHost) { + this.maxConnPerHost = maxConnPerHost; + } + + /** + * 最大总连接数,默认50 + * + * @param maxTotalConn + * 最大总连接数,默认50 + */ + public void setMaxTotalConn(int maxTotalConn) { + this.maxTotalConn = maxTotalConn; + } + + /** + * 自定义httpclient的User Agent + * + * @param userAgent + * User Agent + */ + public void setUserAgent(String userAgent) { + this.userAgent = userAgent; + } + + public IdleConnectionMonitorThread getIdleConnectionMonitorThread() { + return this.idleConnectionMonitorThread; + } + + private synchronized void prepare() { + if (prepared.get()) { + return; + } + Registry registry = RegistryBuilder.create() + .register("http", this.plainConnectionSocketFactory).register("https", this.sslConnectionSocketFactory) + .build(); + + @SuppressWarnings("resource") + PoolingHttpClientConnectionManager connectionManager; + if(dnsResover != null){ + if(log.isDebugEnabled()){ + log.debug("specified dns resolver."); + } + connectionManager = new PoolingHttpClientConnectionManager(registry, dnsResover); + }else{ + if(log.isDebugEnabled()){ + log.debug("Not specified dns resolver."); + } + connectionManager = new PoolingHttpClientConnectionManager(registry); + } + + connectionManager.setMaxTotal(this.maxTotalConn); + connectionManager.setDefaultMaxPerRoute(this.maxConnPerHost); + connectionManager + .setDefaultSocketConfig(SocketConfig.copy(SocketConfig.DEFAULT).setSoTimeout(this.soTimeout).build()); + + this.idleConnectionMonitorThread = new IdleConnectionMonitorThread(connectionManager, this.idleConnTimeout, + this.checkWaitTime); + this.idleConnectionMonitorThread.setDaemon(true); + this.idleConnectionMonitorThread.start(); + + this.httpClientBuilder = HttpClients.custom().setConnectionManager(connectionManager) + .setConnectionManagerShared(true) + .setDefaultRequestConfig(RequestConfig.custom().setSocketTimeout(this.soTimeout) + .setConnectTimeout(this.connectionTimeout) + .setConnectionRequestTimeout(this.connectionRequestTimeout).build()) + .setRetryHandler(this.httpRequestRetryHandler); + + if (StringUtils.isNotBlank(this.httpProxyHost) && StringUtils.isNotBlank(this.httpProxyUsername)) { + // 使用代理服务器 需要用户认证的代理服务器 + CredentialsProvider provider = new BasicCredentialsProvider(); + provider.setCredentials(new AuthScope(this.httpProxyHost, this.httpProxyPort), + new UsernamePasswordCredentials(this.httpProxyUsername, this.httpProxyPassword)); + this.httpClientBuilder.setDefaultCredentialsProvider(provider); + } + + if (StringUtils.isNotBlank(this.userAgent)) { + this.httpClientBuilder.setUserAgent(this.userAgent); + } + prepared.set(true); + } + + @Override + public CloseableHttpClient build() { + if (!prepared.get()) { + prepare(); + } + return this.httpClientBuilder.build(); + } + + public static class IdleConnectionMonitorThread extends Thread { + private final HttpClientConnectionManager connMgr; + private final int idleConnTimeout; + private final int checkWaitTime; + private volatile boolean shutdown; + + public IdleConnectionMonitorThread(HttpClientConnectionManager connMgr, int idleConnTimeout, + int checkWaitTime) { + super("IdleConnectionMonitorThread"); + this.connMgr = connMgr; + this.idleConnTimeout = idleConnTimeout; + this.checkWaitTime = checkWaitTime; + } + + @Override + public void run() { + try { + while (!this.shutdown) { + synchronized (this) { + wait(this.checkWaitTime); + this.connMgr.closeExpiredConnections(); + this.connMgr.closeIdleConnections(this.idleConnTimeout, TimeUnit.MILLISECONDS); + } + } + } catch (InterruptedException ignore) { + } + } + + public void trigger() { + synchronized (this) { + notifyAll(); + } + } + + public void shutdown() { + this.shutdown = true; + synchronized (this) { + notifyAll(); + } + } + } + + public DnsResolver getDnsResover() { + return dnsResover; + } + + public void setDnsResover(DnsResolver dnsResover) { + this.dnsResover = dnsResover; + } + +} diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/WxDnsResolver.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/WxDnsResolver.java new file mode 100644 index 00000000..315bf6f6 --- /dev/null +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/WxDnsResolver.java @@ -0,0 +1,64 @@ +package me.chanjar.weixin.common.util.http; + +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.HashMap; +import java.util.Map; + +import org.apache.http.conn.DnsResolver; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * 微信DNS域名解析器,将微信域名绑定到指定IP + * -------------------------------------------- + * 适用于服务器端调用微信服务器需要开通出口防火墙情况 + * + * Created by Andy Huo on 17/03/28. + */ +public class WxDnsResolver implements DnsResolver { + + protected final Logger log = LoggerFactory.getLogger(WxDnsResolver.class); + + private static Map MAPPINGS = new HashMap(); + + private final static String WECHAT_API_URL = "api.weixin.qq.com"; + + private String wxApiIp; + + public WxDnsResolver(String ip){ + + this.wxApiIp = ip; + this.init(); + } + + private void init(){ + if(log.isDebugEnabled()){ + log.debug("init wechat dns config with ip {}", wxApiIp); + } + try { + MAPPINGS.put(WECHAT_API_URL, new InetAddress[]{InetAddress.getByName(wxApiIp)}); + } catch (UnknownHostException e) { + //如果初始化DNS配置失败则使用默认配置,不影响服务的启动 + log.error("init WxDnsResolver error", e); + MAPPINGS = new HashMap(); + } + + } + + @Override + public InetAddress[] resolve(String host) throws UnknownHostException { + + + return MAPPINGS.containsKey(host) ? MAPPINGS.get(host) : new InetAddress[0]; + } + + public String getWxApiIp() { + return wxApiIp; + } + + public void setWxApiIp(String wxApiIp) { + this.wxApiIp = wxApiIp; + this.init(); + } +} From b2c4160e37d498ef43b8430e11a1bb34f7fecca7 Mon Sep 17 00:00:00 2001 From: Binary Wang Date: Wed, 10 May 2017 11:28:04 +0800 Subject: [PATCH 04/13] =?UTF-8?q?=E6=B7=BB=E5=8A=A0DNS=E8=A7=A3=E6=9E=90?= =?UTF-8?q?=E5=99=A8=E6=94=AF=E6=8C=81=20(#171)=20fix?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../common/util/http/{ => apache}/ApacheHttpDnsClientBuilder.java | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/{ => apache}/ApacheHttpDnsClientBuilder.java (100%) diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/ApacheHttpDnsClientBuilder.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheHttpDnsClientBuilder.java similarity index 100% rename from weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/ApacheHttpDnsClientBuilder.java rename to weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheHttpDnsClientBuilder.java From a6d29d9c30799bfd2590838e80fdc2b5dc318dd1 Mon Sep 17 00:00:00 2001 From: Binary Wang Date: Wed, 10 May 2017 11:28:35 +0800 Subject: [PATCH 05/13] =?UTF-8?q?=E6=B7=BB=E5=8A=A0DNS=E8=A7=A3=E6=9E=90?= =?UTF-8?q?=E5=99=A8=E6=94=AF=E6=8C=81=20(#171)=20fix?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../util/http/apache/ApacheHttpDnsClientBuilder.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheHttpDnsClientBuilder.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheHttpDnsClientBuilder.java index e98fce64..6f069822 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheHttpDnsClientBuilder.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheHttpDnsClientBuilder.java @@ -1,4 +1,4 @@ -package me.chanjar.weixin.common.util.http; +package me.chanjar.weixin.common.util.http.apache; import org.apache.commons.lang3.StringUtils; import org.apache.http.annotation.NotThreadSafe; @@ -30,7 +30,7 @@ import java.util.concurrent.atomic.AtomicBoolean; /** * httpclient 连接管理器 自带DNS解析 - * + * * 大部分代码拷贝自:DefaultApacheHttpClientBuilder * * @author Andy.Huo @@ -62,7 +62,7 @@ public class ApacheHttpDnsClientBuilder implements ApacheHttpClientBuilder { private int httpProxyPort; private String httpProxyUsername; private String httpProxyPassword; - + /** * 闲置连接监控线程 */ @@ -207,7 +207,7 @@ public class ApacheHttpDnsClientBuilder implements ApacheHttpClientBuilder { Registry registry = RegistryBuilder.create() .register("http", this.plainConnectionSocketFactory).register("https", this.sslConnectionSocketFactory) .build(); - + @SuppressWarnings("resource") PoolingHttpClientConnectionManager connectionManager; if(dnsResover != null){ @@ -221,7 +221,7 @@ public class ApacheHttpDnsClientBuilder implements ApacheHttpClientBuilder { } connectionManager = new PoolingHttpClientConnectionManager(registry); } - + connectionManager.setMaxTotal(this.maxTotalConn); connectionManager.setDefaultMaxPerRoute(this.maxConnPerHost); connectionManager From c21bad9e1df34216a48726688d6fe30bb464602c Mon Sep 17 00:00:00 2001 From: Binary Wang Date: Wed, 10 May 2017 11:55:39 +0800 Subject: [PATCH 06/13] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E8=AE=BE=E7=BD=AE?= =?UTF-8?q?=E6=96=B9=E6=B3=95=EF=BC=8C=E6=96=B9=E4=BE=BF=E8=AE=BE=E7=BD=AE?= =?UTF-8?q?=E6=98=AF=E5=90=A6=E4=BD=BF=E7=94=A8=E5=BE=AE=E4=BF=A1=E6=94=AF?= =?UTF-8?q?=E4=BB=98=E4=BB=BF=E7=9C=9F=E6=B5=8B=E8=AF=95=E7=8E=AF=E5=A2=83?= =?UTF-8?q?=20#224?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../github/binarywang/wxpay/config/WxPayConfig.java | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/config/WxPayConfig.java b/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/config/WxPayConfig.java index 895a827a..c05cd7e7 100644 --- a/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/config/WxPayConfig.java +++ b/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/config/WxPayConfig.java @@ -22,6 +22,7 @@ public class WxPayConfig { private String tradeType; private SSLContext sslContext; private String keyPath; + private boolean useSandboxEnv = false; public void setNotifyUrl(String notifyUrl) { this.notifyUrl = notifyUrl; @@ -130,7 +131,14 @@ public class WxPayConfig { * 默认不使用 */ public boolean useSandbox() { - return false; + return this.useSandboxEnv; + } + + /** + * 设置是否使用沙箱仿真测试环境 + */ + public void setUseSandboxEnv(boolean useSandboxEnv) { + this.useSandboxEnv = useSandboxEnv; } public SSLContext initSSLContext() { From f2161675417fa22e54cfdb0999d245571fd7c41b Mon Sep 17 00:00:00 2001 From: Binary Wang Date: Wed, 10 May 2017 12:02:48 +0800 Subject: [PATCH 07/13] =?UTF-8?q?WxConsts=E5=A2=9E=E5=8A=A0=E5=BE=AE?= =?UTF-8?q?=E4=BF=A1=E6=8E=A8=E9=80=81=E4=BC=9A=E5=91=98=E5=8D=A1=E5=86=85?= =?UTF-8?q?=E5=AE=B9=E6=9B=B4=E6=96=B0=E4=BA=8B=E4=BB=B6update=5Fmember=5F?= =?UTF-8?q?card=E5=B8=B8=E9=87=8F=20#217?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../main/java/me/chanjar/weixin/common/api/WxConsts.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxConsts.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxConsts.java index 2581950d..274252f5 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxConsts.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxConsts.java @@ -101,9 +101,17 @@ public class WxConsts { public static final String EVT_USER_VIEW_CARD = "user_view_card"; public static final String EVT_USER_ENTER_SESSION_FROM_CARD = "user_enter_session_from_card"; public static final String EVT_CARD_SKU_REMIND = "card_sku_remind"; // 库存报警 + /** + * 会员卡内容更新事件 + */ + public static final String EVT_UPDATE_MEMBER_CARD = "update_member_card"; + + + //以下为客服相关事件 public static final String EVT_KF_CREATE_SESSION = "kf_create_session"; // 客服接入会话 public static final String EVT_KF_CLOSE_SESSION = "kf_close_session"; // 客服关闭会话 public static final String EVT_KF_SWITCH_SESSION = "kf_switch_session"; // 客服转接会话 + public static final String EVT_POI_CHECK_NOTIFY = "poi_check_notify"; //门店审核事件推送 public static final String EVT_SUBMIT_MEMBERCARD_USER_INFO = "submit_membercard_user_info"; //接收会员信息事件推送 From ba87eebf6575c7360890fb84d8373d36ad91980f Mon Sep 17 00:00:00 2001 From: Binary Wang Date: Wed, 10 May 2017 12:05:00 +0800 Subject: [PATCH 08/13] =?UTF-8?q?WxConsts=E5=A2=9E=E5=8A=A0=E5=BE=AE?= =?UTF-8?q?=E4=BF=A1=E6=8E=A8=E9=80=81=E5=88=B8=E7=82=B9=E6=B5=81=E6=B0=B4?= =?UTF-8?q?=E8=AF=A6=E6=83=85card=5Fpay=5Forder=E4=BA=8B=E4=BB=B6=E5=B8=B8?= =?UTF-8?q?=E9=87=8F=20#219?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../main/java/me/chanjar/weixin/common/api/WxConsts.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxConsts.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxConsts.java index 274252f5..66085748 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxConsts.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxConsts.java @@ -88,6 +88,8 @@ public class WxConsts { public static final String EVT_LOCATION_SELECT = "location_select"; public static final String EVT_TEMPLATESENDJOBFINISH = "TEMPLATESENDJOBFINISH"; public static final String EVT_ENTER_AGENT = "enter_agent"; + + //以下为卡券相关事件 public static final String EVT_CARD_PASS_CHECK = "card_pass_check"; public static final String EVT_CARD_NOT_PASS_CHECK = "card_not_pass_check"; public static final String EVT_USER_GET_CARD = "user_get_card"; @@ -105,7 +107,10 @@ public class WxConsts { * 会员卡内容更新事件 */ public static final String EVT_UPDATE_MEMBER_CARD = "update_member_card"; - + /** + * 券点流水详情事件 + */ + public static final String EVT_CARD_PAY_ORDER = "card_pay_order"; //以下为客服相关事件 public static final String EVT_KF_CREATE_SESSION = "kf_create_session"; // 客服接入会话 From 951913b4933107e644087dc3b4877e1c2c1b6c2f Mon Sep 17 00:00:00 2001 From: Binary Wang Date: Wed, 10 May 2017 12:07:21 +0800 Subject: [PATCH 09/13] =?UTF-8?q?WxConsts=E5=A2=9E=E5=8A=A0=E5=BE=AE?= =?UTF-8?q?=E4=BF=A1=E6=8E=A8=E9=80=81=E6=91=87=E4=B8=80=E6=91=87=E4=BA=8B?= =?UTF-8?q?=E4=BB=B6=E9=80=9A=E7=9F=A5ShakearoundUserShake=E4=BA=8B?= =?UTF-8?q?=E4=BB=B6=E5=B8=B8=E9=87=8F=20#220?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/main/java/me/chanjar/weixin/common/api/WxConsts.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxConsts.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxConsts.java index 66085748..b1e997fb 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxConsts.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxConsts.java @@ -146,6 +146,11 @@ public class WxConsts { */ public static final String EVT_VERIFY_EXPIRED = "verify_expired"; + /** + * 微信摇一摇周边>>摇一摇事件通知 + */ + public static final String EVT_SHAKEAROUND_USER_SHAKE = "ShakearoundUserShake"; + /////////////////////// // 上传多媒体文件的类型 /////////////////////// From 25cf3705aaa0d83d0ac971e43a02733ff9b6f837 Mon Sep 17 00:00:00 2001 From: Binary Wang Date: Wed, 10 May 2017 12:15:26 +0800 Subject: [PATCH 10/13] =?UTF-8?q?=E5=B0=86=E5=85=AC=E4=BC=97=E5=8F=B7?= =?UTF-8?q?=E7=9B=B8=E5=85=B3=E7=9A=84=E4=BA=8B=E4=BB=B6=E5=B8=B8=E9=87=8F?= =?UTF-8?q?=E6=8A=BD=E5=8F=96=E5=87=BA=E6=9D=A5=EF=BC=8C=E5=8D=95=E7=8B=AC?= =?UTF-8?q?=E6=94=BE=E4=BA=8EWxMpEventConstants=E7=B1=BB=E4=B8=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chanjar/weixin/common/api/WxConsts.java | 63 ---------------- .../mp/constant/WxMpEventConstants.java | 72 +++++++++++++++++++ 2 files changed, 72 insertions(+), 63 deletions(-) create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/constant/WxMpEventConstants.java diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxConsts.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxConsts.java index b1e997fb..e04dc456 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxConsts.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxConsts.java @@ -24,7 +24,6 @@ public class WxConsts { public static final String XML_MSG_HARDWARE = "hardware"; public static final String XML_TRANSFER_CUSTOMER_SERVICE = "transfer_customer_service"; - /////////////////////// // 主动发送消息(即客服消息)的消息类型 /////////////////////// @@ -89,68 +88,6 @@ public class WxConsts { public static final String EVT_TEMPLATESENDJOBFINISH = "TEMPLATESENDJOBFINISH"; public static final String EVT_ENTER_AGENT = "enter_agent"; - //以下为卡券相关事件 - public static final String EVT_CARD_PASS_CHECK = "card_pass_check"; - public static final String EVT_CARD_NOT_PASS_CHECK = "card_not_pass_check"; - public static final String EVT_USER_GET_CARD = "user_get_card"; - /** - * 卡券转赠事件 - */ - public static final String EVT_USER_GIFTING_CARD = "user_gifting_card"; - public static final String EVT_USER_DEL_CARD = "user_del_card"; - public static final String EVT_USER_CONSUME_CARD = "user_consume_card"; - public static final String EVT_USER_PAY_FROM_PAY_CELL = "user_pay_from_pay_cell"; - public static final String EVT_USER_VIEW_CARD = "user_view_card"; - public static final String EVT_USER_ENTER_SESSION_FROM_CARD = "user_enter_session_from_card"; - public static final String EVT_CARD_SKU_REMIND = "card_sku_remind"; // 库存报警 - /** - * 会员卡内容更新事件 - */ - public static final String EVT_UPDATE_MEMBER_CARD = "update_member_card"; - /** - * 券点流水详情事件 - */ - public static final String EVT_CARD_PAY_ORDER = "card_pay_order"; - - //以下为客服相关事件 - public static final String EVT_KF_CREATE_SESSION = "kf_create_session"; // 客服接入会话 - public static final String EVT_KF_CLOSE_SESSION = "kf_close_session"; // 客服关闭会话 - public static final String EVT_KF_SWITCH_SESSION = "kf_switch_session"; // 客服转接会话 - - public static final String EVT_POI_CHECK_NOTIFY = "poi_check_notify"; //门店审核事件推送 - public static final String EVT_SUBMIT_MEMBERCARD_USER_INFO = "submit_membercard_user_info"; //接收会员信息事件推送 - - //以下为微信认证事件 - /** - * 资质认证成功 - */ - public static final String EVT_QUALIFICATION_VERIFY_SUCCESS = "qualification_verify_success"; - /** - * 资质认证失败 - */ - public static final String EVT_QUALIFICATION_VERIFY_FAIL = "qualification_verify_fail"; - /** - * 名称认证成功 - */ - public static final String EVT_NAMING_VERIFY_SUCCESS = "naming_verify_success"; - /** - * 名称认证失败 - */ - public static final String EVT_NAMING_VERIFY_FAIL = "naming_verify_fail"; - /** - * 年审通知 - */ - public static final String EVT_ANNUAL_RENEW = "annual_renew"; - /** - * 认证过期失效通知 - */ - public static final String EVT_VERIFY_EXPIRED = "verify_expired"; - - /** - * 微信摇一摇周边>>摇一摇事件通知 - */ - public static final String EVT_SHAKEAROUND_USER_SHAKE = "ShakearoundUserShake"; - /////////////////////// // 上传多媒体文件的类型 /////////////////////// diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/constant/WxMpEventConstants.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/constant/WxMpEventConstants.java new file mode 100644 index 00000000..a75edf07 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/constant/WxMpEventConstants.java @@ -0,0 +1,72 @@ +package me.chanjar.weixin.mp.constant; + +/** + *
+ * 微信公众号事件的相关常量
+ * Created by Binary Wang on 2017-5-10.
+ * @author binarywang(Binary Wang)
+ * 
+ */ +public class WxMpEventConstants { + //以下为卡券相关事件 + public static final String EVT_CARD_PASS_CHECK = "card_pass_check"; + public static final String EVT_CARD_NOT_PASS_CHECK = "card_not_pass_check"; + public static final String EVT_USER_GET_CARD = "user_get_card"; + /** + * 卡券转赠事件 + */ + public static final String EVT_USER_GIFTING_CARD = "user_gifting_card"; + public static final String EVT_USER_DEL_CARD = "user_del_card"; + public static final String EVT_USER_CONSUME_CARD = "user_consume_card"; + public static final String EVT_USER_PAY_FROM_PAY_CELL = "user_pay_from_pay_cell"; + public static final String EVT_USER_VIEW_CARD = "user_view_card"; + public static final String EVT_USER_ENTER_SESSION_FROM_CARD = "user_enter_session_from_card"; + public static final String EVT_CARD_SKU_REMIND = "card_sku_remind"; // 库存报警 + /** + * 会员卡内容更新事件 + */ + public static final String EVT_UPDATE_MEMBER_CARD = "update_member_card"; + /** + * 券点流水详情事件 + */ + public static final String EVT_CARD_PAY_ORDER = "card_pay_order"; + + //以下为客服相关事件 + public static final String EVT_KF_CREATE_SESSION = "kf_create_session"; // 客服接入会话 + public static final String EVT_KF_CLOSE_SESSION = "kf_close_session"; // 客服关闭会话 + public static final String EVT_KF_SWITCH_SESSION = "kf_switch_session"; // 客服转接会话 + public static final String EVT_POI_CHECK_NOTIFY = "poi_check_notify"; //门店审核事件推送 + public static final String EVT_SUBMIT_MEMBERCARD_USER_INFO = "submit_membercard_user_info"; //接收会员信息事件推送 + + //以下为微信认证事件 + /** + * 资质认证成功 + */ + public static final String EVT_QUALIFICATION_VERIFY_SUCCESS = "qualification_verify_success"; + /** + * 资质认证失败 + */ + public static final String EVT_QUALIFICATION_VERIFY_FAIL = "qualification_verify_fail"; + /** + * 名称认证成功 + */ + public static final String EVT_NAMING_VERIFY_SUCCESS = "naming_verify_success"; + /** + * 名称认证失败 + */ + public static final String EVT_NAMING_VERIFY_FAIL = "naming_verify_fail"; + /** + * 年审通知 + */ + public static final String EVT_ANNUAL_RENEW = "annual_renew"; + /** + * 认证过期失效通知 + */ + public static final String EVT_VERIFY_EXPIRED = "verify_expired"; + + //以下为微信摇一摇相关事件 + /** + * 微信摇一摇周边>>摇一摇事件通知 + */ + public static final String EVT_SHAKEAROUND_USER_SHAKE = "ShakearoundUserShake"; +} From 5f887739a3ec8c6ffbb32316e5cfd44ea841a3d8 Mon Sep 17 00:00:00 2001 From: Binary Wang Date: Wed, 10 May 2017 14:49:42 +0800 Subject: [PATCH 11/13] =?UTF-8?q?=E4=BA=8B=E4=BB=B6=E5=B8=B8=E9=87=8F?= =?UTF-8?q?=E6=A0=B9=E6=8D=AE=E5=88=86=E7=B1=BB=E5=88=9B=E5=BB=BA=E9=9D=99?= =?UTF-8?q?=E6=80=81=E5=86=85=E9=83=A8=E7=B1=BB=E8=BF=9B=E8=A1=8C=E7=AE=A1?= =?UTF-8?q?=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mp/constant/WxMpEventConstants.java | 133 ++++++++++++------ 1 file changed, 87 insertions(+), 46 deletions(-) diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/constant/WxMpEventConstants.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/constant/WxMpEventConstants.java index a75edf07..77058bad 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/constant/WxMpEventConstants.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/constant/WxMpEventConstants.java @@ -8,65 +8,106 @@ package me.chanjar.weixin.mp.constant; * */ public class WxMpEventConstants { - //以下为卡券相关事件 - public static final String EVT_CARD_PASS_CHECK = "card_pass_check"; - public static final String EVT_CARD_NOT_PASS_CHECK = "card_not_pass_check"; - public static final String EVT_USER_GET_CARD = "user_get_card"; /** - * 卡券转赠事件 + * 门店审核事件 */ - public static final String EVT_USER_GIFTING_CARD = "user_gifting_card"; - public static final String EVT_USER_DEL_CARD = "user_del_card"; - public static final String EVT_USER_CONSUME_CARD = "user_consume_card"; - public static final String EVT_USER_PAY_FROM_PAY_CELL = "user_pay_from_pay_cell"; - public static final String EVT_USER_VIEW_CARD = "user_view_card"; - public static final String EVT_USER_ENTER_SESSION_FROM_CARD = "user_enter_session_from_card"; - public static final String EVT_CARD_SKU_REMIND = "card_sku_remind"; // 库存报警 + public static final String POI_CHECK_NOTIFY = "poi_check_notify"; + /** - * 会员卡内容更新事件 + * 接收会员信息事件 */ - public static final String EVT_UPDATE_MEMBER_CARD = "update_member_card"; + public static final String SUBMIT_MEMBERCARD_USER_INFO = "submit_membercard_user_info"; + /** - * 券点流水详情事件 + * 微信摇一摇周边>>摇一摇事件通知 */ - public static final String EVT_CARD_PAY_ORDER = "card_pay_order"; + public static final String SHAKEAROUND_USER_SHAKE = "ShakearoundUserShake"; - //以下为客服相关事件 - public static final String EVT_KF_CREATE_SESSION = "kf_create_session"; // 客服接入会话 - public static final String EVT_KF_CLOSE_SESSION = "kf_close_session"; // 客服关闭会话 - public static final String EVT_KF_SWITCH_SESSION = "kf_switch_session"; // 客服转接会话 - public static final String EVT_POI_CHECK_NOTIFY = "poi_check_notify"; //门店审核事件推送 - public static final String EVT_SUBMIT_MEMBERCARD_USER_INFO = "submit_membercard_user_info"; //接收会员信息事件推送 - //以下为微信认证事件 - /** - * 资质认证成功 - */ - public static final String EVT_QUALIFICATION_VERIFY_SUCCESS = "qualification_verify_success"; - /** - * 资质认证失败 - */ - public static final String EVT_QUALIFICATION_VERIFY_FAIL = "qualification_verify_fail"; - /** - * 名称认证成功 - */ - public static final String EVT_NAMING_VERIFY_SUCCESS = "naming_verify_success"; - /** - * 名称认证失败 - */ - public static final String EVT_NAMING_VERIFY_FAIL = "naming_verify_fail"; /** - * 年审通知 + * 卡券相关事件 */ - public static final String EVT_ANNUAL_RENEW = "annual_renew"; + public static class Card { + public static final String CARD_PASS_CHECK = "card_pass_check"; + public static final String CARD_NOT_PASS_CHECK = "card_not_pass_check"; + public static final String USER_GET_CARD = "user_get_card"; + public static final String USER_DEL_CARD = "user_del_card"; + public static final String USER_CONSUME_CARD = "user_consume_card"; + public static final String USER_PAY_FROM_PAY_CELL = "user_pay_from_pay_cell"; + public static final String USER_VIEW_CARD = "user_view_card"; + public static final String USER_ENTER_SESSION_FROM_CARD = "user_enter_session_from_card"; + + /** + * 卡券转赠事件 + */ + public static final String USER_GIFTING_CARD = "user_gifting_card"; + + /** + * 库存报警 + */ + public static final String CARD_SKU_REMIND = "card_sku_remind"; + + /** + * 会员卡内容更新事件 + */ + public static final String UPDATE_MEMBER_CARD = "update_member_card"; + + /** + * 券点流水详情事件 + */ + public static final String CARD_PAY_ORDER = "card_pay_order"; + } + + /** - * 认证过期失效通知 + * 客服相关事件 */ - public static final String EVT_VERIFY_EXPIRED = "verify_expired"; + public static class CustomerService { + /** + * 客服接入会话 + */ + public static final String KF_CREATE_SESSION = "kf_create_session"; + + /** + * 客服关闭会话 + */ + public static final String KF_CLOSE_SESSION = "kf_close_session"; + + /** + * 客服转接会话 + */ + public static final String KF_SWITCH_SESSION = "kf_switch_session"; + } - //以下为微信摇一摇相关事件 /** - * 微信摇一摇周边>>摇一摇事件通知 + * 微信认证事件 */ - public static final String EVT_SHAKEAROUND_USER_SHAKE = "ShakearoundUserShake"; + public static class Qualification { + + /** + * 资质认证成功 + */ + public static final String QUALIFICATION_VERIFY_SUCCESS = "qualification_verify_success"; + /** + * 资质认证失败 + */ + public static final String QUALIFICATION_VERIFY_FAIL = "qualification_verify_fail"; + /** + * 名称认证成功 + */ + public static final String NAMING_VERIFY_SUCCESS = "naming_verify_success"; + /** + * 名称认证失败 + */ + public static final String NAMING_VERIFY_FAIL = "naming_verify_fail"; + /** + * 年审通知 + */ + public static final String ANNUAL_RENEW = "annual_renew"; + /** + * 认证过期失效通知 + */ + public static final String VERIFY_EXPIRED = "verify_expired"; + } + } From 8982cf8471decae485596d3cab63060407230c93 Mon Sep 17 00:00:00 2001 From: Binary Wang Date: Thu, 11 May 2017 17:07:08 +0800 Subject: [PATCH 12/13] =?UTF-8?q?=E6=89=B9=E9=87=8F=E6=A0=BC=E5=BC=8F?= =?UTF-8?q?=E5=8C=96=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle | 22 +- pom.xml | 3 +- weixin-java-common/build.gradle | 15 +- weixin-java-common/pom.xml | 4 +- .../weixin/common/annotation/Required.java | 6 +- .../bean/result/WxMediaUploadResult.java | 2 +- .../session/StandardSessionManager.java | 12 +- .../TooManyActiveSessionsException.java | 2 +- .../weixin/common/util/ToStringUtils.java | 34 +- .../weixin/common/util/crypto/SHA1.java | 4 +- .../common/util/crypto/WxCryptUtil.java | 149 ++--- .../weixin/common/util/fs/FileUtils.java | 4 +- .../http/MediaDownloadRequestExecutor.java | 45 +- .../util/http/MediaUploadRequestExecutor.java | 33 +- .../common/util/http/RequestExecutor.java | 26 +- .../weixin/common/util/http/RequestHttp.java | 5 +- .../util/http/SimpleGetRequestExecutor.java | 31 +- .../util/http/SimplePostRequestExecutor.java | 31 +- .../common/util/http/WxDnsResolver.java | 89 ++- .../http/apache/ApacheHttpClientBuilder.java | 1 + .../apache/ApacheHttpDnsClientBuilder.java | 540 +++++++++--------- .../ApacheMediaDownloadRequestExecutor.java | 23 +- .../ApacheMediaUploadRequestExecutor.java | 16 +- .../ApacheSimpleGetRequestExecutor.java | 12 +- .../ApacheSimplePostRequestExecutor.java | 12 +- .../DefaultApacheHttpClientBuilder.java | 4 +- .../JoddMediaDownloadRequestExecutor.java | 18 +- .../jodd/JoddMediaUploadRequestExecutor.java | 7 +- .../jodd/JoddSimpleGetRequestExecutor.java | 12 +- .../jodd/JoddSimplePostRequestExecutor.java | 7 +- .../OkMediaDownloadRequestExecutor.java | 19 +- .../okhttp/OkMediaUploadRequestExecutor.java | 7 +- .../okhttp/OkSimpleGetRequestExecutor.java | 11 +- .../okhttp/OkSimplePostRequestExecutor.java | 11 +- .../util/http/okhttp/OkhttpProxyInfo.java | 24 +- .../common/util/json/WxGsonBuilder.java | 1 - .../weixin/common/util/res/StringManager.java | 8 +- .../common/util/xml/XStreamInitializer.java | 4 +- .../weixin/common/bean/WxAccessTokenTest.java | 4 +- .../weixin/common/bean/WxErrorTest.java | 4 +- .../weixin/common/bean/WxMenuTest.java | 116 ++-- .../weixin/common/session/SessionTest.java | 7 +- ...WxMessageInMemoryDuplicateCheckerTest.java | 4 +- .../common/util/crypto/WxCryptUtilTest.java | 7 +- .../src/test/resources/logback-test.xml | 4 +- .../src/test/resources/testng.xml | 2 +- weixin-java-cp/build.gradle | 13 +- weixin-java-cp/pom.xml | 3 +- .../weixin/cp/api/WxCpJedisConfigStorage.java | 8 +- .../me/chanjar/weixin/cp/api/WxCpService.java | 14 +- .../cp/api/impl/okhttp/WxCpServiceImpl.java | 4 +- .../me/chanjar/weixin/cp/bean/WxCpDepart.java | 14 +- .../chanjar/weixin/cp/bean/WxCpMessage.java | 16 +- .../me/chanjar/weixin/cp/bean/WxCpTag.java | 4 +- .../me/chanjar/weixin/cp/bean/WxCpUser.java | 4 +- .../weixin/cp/bean/WxCpXmlMessage.java | 96 ++-- .../cp/bean/WxCpXmlOutImageMessage.java | 1 - .../weixin/cp/bean/WxCpXmlOutNewsMessage.java | 7 +- .../weixin/cp/bean/WxCpXmlOutTextMessage.java | 1 - .../cp/bean/WxCpXmlOutVideoMessage.java | 1 - .../cp/bean/WxCpXmlOutVoiceMessage.java | 1 - .../weixin/cp/bean/article/MpnewsArticle.java | 1 + .../cp/bean/messagebuilder/BaseBuilder.java | 2 +- .../weixin/cp/util/crypto/WxCpCryptUtil.java | 98 ++-- .../cp/util/json/WxCpDepartGsonAdapter.java | 2 +- .../cp/util/json/WxCpMessageGsonAdapter.java | 2 +- .../cp/util/json/WxCpTagGsonAdapter.java | 2 +- .../cp/util/json/WxCpUserGsonAdapter.java | 6 +- .../chanjar/weixin/cp/api/ApiTestModule.java | 19 +- .../weixin/cp/api/WxCpDepartAPITest.java | 13 +- .../weixin/cp/api/WxCpMediaAPITest.java | 34 +- .../weixin/cp/api/WxCpMessageRouterTest.java | 91 ++- .../chanjar/weixin/cp/api/WxCpTagAPITest.java | 5 +- .../weixin/cp/api/WxCpUserAPITest.java | 5 +- .../chanjar/weixin/cp/api/WxMenuAPITest.java | 12 +- .../cp/api/impl/apache/WxCpBaseAPITest.java | 5 +- .../cp/api/impl/apache/WxCpBusyRetryTest.java | 7 +- .../api/impl/apache/WxCpMessageAPITest.java | 13 +- .../weixin/cp/bean/WxCpMessageTest.java | 7 +- .../weixin/cp/bean/WxCpXmlMessageTest.java | 90 +-- .../cp/bean/WxCpXmlOutImageMessageTest.java | 42 +- .../cp/bean/WxCpXmlOutNewsMessageTest.java | 108 ++-- .../cp/bean/WxCpXmlOutTextMessageTest.java | 42 +- .../cp/bean/WxCpXmlOutVideoMessageTest.java | 70 +-- .../cp/bean/WxCpXmlOutVoiceMessageTest.java | 42 +- .../demo/WxCpDemoInMemoryConfigStorage.java | 2 +- .../weixin/cp/demo/WxCpDemoServer.java | 45 +- .../weixin/cp/demo/WxCpEndpointServlet.java | 4 +- .../weixin/cp/demo/WxCpOAuth2Servlet.java | 11 +- .../src/test/resources/logback-test.xml | 4 +- .../src/test/resources/test-config.sample.xml | 22 +- weixin-java-mp/build.gradle | 15 +- weixin-java-mp/pom.xml | 3 +- .../weixin/mp/api/WxMpCardService.java | 7 +- .../weixin/mp/api/WxMpDataCubeService.java | 11 +- .../weixin/mp/api/WxMpDeviceService.java | 12 +- .../mp/api/WxMpInMemoryConfigStorage.java | 24 +- .../mp/api/WxMpInRedisConfigStorage.java | 6 +- .../weixin/mp/api/WxMpKefuService.java | 1 + .../weixin/mp/api/WxMpMaterialService.java | 32 +- .../weixin/mp/api/WxMpMenuService.java | 20 +- .../weixin/mp/api/WxMpMessageMatcher.java | 1 + .../weixin/mp/api/WxMpMessageRouter.java | 49 +- .../weixin/mp/api/WxMpMessageRouterRule.java | 42 +- .../weixin/mp/api/WxMpQrcodeService.java | 1 + .../me/chanjar/weixin/mp/api/WxMpService.java | 11 +- .../weixin/mp/api/WxMpStoreService.java | 16 +- .../weixin/mp/api/WxMpTemplateMsgService.java | 1 + .../weixin/mp/api/WxMpUserService.java | 2 +- .../weixin/mp/api/WxMpUserTagService.java | 17 +- .../mp/api/impl/WxMpCardServiceImpl.java | 19 +- .../mp/api/impl/WxMpDataCubeServiceImpl.java | 21 +- .../mp/api/impl/WxMpDeviceServiceImpl.java | 4 +- .../mp/api/impl/WxMpMaterialServiceImpl.java | 2 +- .../mp/api/impl/WxMpStoreServiceImpl.java | 17 +- .../mp/api/impl/WxMpUserServiceImpl.java | 8 +- .../mp/api/impl/WxMpUserTagServiceImpl.java | 13 +- .../chanjar/weixin/mp/bean/WxMpMassNews.java | 10 +- .../mp/bean/WxMpMassOpenIdsMessage.java | 20 +- .../weixin/mp/bean/WxMpMassTagMessage.java | 3 +- .../chanjar/weixin/mp/bean/WxMpMassVideo.java | 4 +- .../weixin/mp/bean/WxMpSemanticQuery.java | 4 +- .../chanjar/weixin/mp/bean/WxMpUserQuery.java | 377 ++++++------ .../datacube/WxDataCubeArticleResult.java | 15 +- .../bean/datacube/WxDataCubeArticleTotal.java | 20 +- .../WxDataCubeArticleTotalDetail.java | 103 ++-- .../bean/datacube/WxDataCubeBaseResult.java | 11 +- .../datacube/WxDataCubeInterfaceResult.java | 20 +- .../mp/bean/datacube/WxDataCubeMsgResult.java | 20 +- .../bean/datacube/WxDataCubeUserCumulate.java | 14 +- .../bean/datacube/WxDataCubeUserSummary.java | 14 +- .../weixin/mp/bean/device/BaseResp.java | 2 +- .../weixin/mp/bean/device/RespMsg.java | 2 +- .../weixin/mp/bean/device/TransMsgResp.java | 2 +- .../bean/device/WxDeviceAuthorizeResult.java | 2 +- .../weixin/mp/bean/device/WxDeviceBind.java | 2 +- .../mp/bean/device/WxDeviceBindResult.java | 2 +- .../weixin/mp/bean/device/WxDeviceMsg.java | 2 +- .../weixin/mp/bean/kefu/WxMpKefuMessage.java | 29 +- .../mp/bean/kefu/result/WxMpKfInfo.java | 4 +- .../mp/bean/kefu/result/WxMpKfList.java | 11 +- .../mp/bean/kefu/result/WxMpKfMsgList.java | 8 +- .../mp/bean/kefu/result/WxMpKfMsgRecord.java | 2 +- .../mp/bean/kefu/result/WxMpKfOnlineList.java | 11 +- .../mp/bean/kefu/result/WxMpKfSession.java | 2 - .../kefu/result/WxMpKfSessionGetResult.java | 10 +- .../bean/kefu/result/WxMpKfSessionList.java | 12 +- .../result/WxMpKfSessionWaitCaseList.java | 12 +- .../mp/bean/material/WxMpMaterialNews.java | 16 +- .../material/WxMpMaterialUploadResult.java | 8 +- .../material/WxMpMaterialVideoInfoResult.java | 8 +- .../weixin/mp/bean/menu/WxMpSelfMenuInfo.java | 80 ++- .../bean/message/WxMpXmlOutImageMessage.java | 8 +- .../mp/bean/message/WxMpXmlOutMessage.java | 98 ++-- .../bean/message/WxMpXmlOutMusicMessage.java | 10 +- .../bean/message/WxMpXmlOutNewsMessage.java | 14 +- .../bean/message/WxMpXmlOutTextMessage.java | 2 +- .../WxMpXmlOutTransferKefuMessage.java | 2 +- .../bean/message/WxMpXmlOutVideoMessage.java | 8 +- .../mp/bean/result/WxMpMassSendResult.java | 10 +- .../mp/bean/result/WxMpMassUploadResult.java | 12 +- .../mp/bean/result/WxMpOAuth2AccessToken.java | 28 +- .../mp/bean/result/WxMpQrCodeTicket.java | 14 +- .../bean/result/WxMpSemanticQueryResult.java | 12 +- .../weixin/mp/bean/result/WxMpUser.java | 28 +- .../weixin/mp/bean/result/WxMpUserList.java | 20 +- .../mp/bean/store/WxMpStoreBaseInfo.java | 201 +++---- .../weixin/mp/bean/store/WxMpStoreInfo.java | 6 +- .../mp/bean/store/WxMpStoreListResult.java | 23 +- .../weixin/mp/bean/tag/WxTagListUser.java | 45 +- .../chanjar/weixin/mp/bean/tag/WxUserTag.java | 26 +- .../weixin/mp/bean/template/WxMpTemplate.java | 28 +- .../bean/template/WxMpTemplateIndustry.java | 58 +- .../mp/bean/template/WxMpTemplateMessage.java | 9 +- .../weixin/mp/builder/kefu/BaseBuilder.java | 2 +- .../weixin/mp/builder/kefu/ImageBuilder.java | 2 +- .../weixin/mp/builder/kefu/MpNewsBuilder.java | 2 +- .../weixin/mp/builder/kefu/NewsBuilder.java | 2 +- .../weixin/mp/builder/kefu/TextBuilder.java | 2 +- .../weixin/mp/builder/kefu/VideoBuilder.java | 2 +- .../weixin/mp/builder/kefu/VoiceBuilder.java | 2 +- .../weixin/mp/builder/kefu/WxCardBuilder.java | 2 +- .../weixin/mp/builder/outxml/BaseBuilder.java | 4 +- .../mp/builder/outxml/ImageBuilder.java | 1 + .../weixin/mp/builder/outxml/NewsBuilder.java | 3 +- .../weixin/mp/builder/outxml/TextBuilder.java | 2 +- .../TransferCustomerServiceBuilder.java | 2 +- .../mp/builder/outxml/VideoBuilder.java | 4 +- .../mp/builder/outxml/VoiceBuilder.java | 1 + .../mp/constant/WxMpEventConstants.java | 2 +- .../weixin/mp/util/crypto/WxMpCryptUtil.java | 86 +-- .../http/MaterialDeleteRequestExecutor.java | 35 +- .../http/MaterialNewsInfoRequestExecutor.java | 36 +- .../http/MaterialUploadRequestExecutor.java | 37 +- .../MaterialVideoInfoRequestExecutor.java | 34 +- ...lVoiceAndImageDownloadRequestExecutor.java | 23 - .../http/MediaImgUploadRequestExecutor.java | 36 +- .../mp/util/http/QrCodeRequestExecutor.java | 37 +- .../ApacheMaterialDeleteRequestExecutor.java | 21 +- ...ApacheMaterialNewsInfoRequestExecutor.java | 23 +- .../ApacheMaterialUploadRequestExecutor.java | 27 +- ...pacheMaterialVideoInfoRequestExecutor.java | 23 +- ...lVoiceAndImageDownloadRequestExecutor.java | 27 +- .../ApacheMediaImgUploadRequestExecutor.java | 19 +- .../apache/ApacheQrCodeRequestExecutor.java | 29 +- .../json/WxMpTemplateMessageGsonAdapter.java | 2 +- .../mp/util/xml/XStreamTransformer.java | 3 +- .../weixin/mp/api/WxMpBusyRetryTest.java | 5 +- .../weixin/mp/api/test/ApiTestModule.java | 1 - .../weixin/mp/demo/WxMpDemoServer.java | 1 - .../src/test/resources/logback-test.xml | 4 +- weixin-java-mp/src/test/resources/testng.xml | 50 +- weixin-java-osgi/pom.xml | 7 +- .../wxpay/bean/WxPayOrderNotifyResponse.java | 1 - .../wxpay/bean/request/WxPayBaseRequest.java | 37 +- .../bean/request/WxPayRefundRequest.java | 27 +- .../bean/request/WxPayShorturlRequest.java | 10 +- .../bean/result/WxScanPayNotifyResult.java | 48 +- .../binarywang/wxpay/config/WxPayConfig.java | 69 +-- .../wxpay/service/WxPayService.java | 8 +- .../wxpay/service/impl/WxPayServiceImpl.java | 2 +- .../binarywang/wxpay/util/SignUtils.java | 6 +- .../service/impl/WxPayServiceImplTest.java | 7 +- 223 files changed, 2361 insertions(+), 2729 deletions(-) diff --git a/build.gradle b/build.gradle index 23ec2c52..6fa9a27a 100644 --- a/build.gradle +++ b/build.gradle @@ -1,4 +1,4 @@ -allprojects { +allprojects { apply plugin: 'maven' group = 'com.github.binarywang' @@ -19,15 +19,15 @@ subprojects { dependencies { - compile group: 'org.slf4j', name: 'slf4j-api', version:'1.7.10' - compile group: 'org.apache.httpcomponents', name: 'httpmime', version:'4.5' - compile group: 'org.apache.httpcomponents', name: 'httpclient', version:'4.5' - compile group: 'com.google.code.gson', name: 'gson', version:'2.7' - compile group: 'com.google.guava', name: 'guava', version:'19.0' - compile group: 'commons-codec', name: 'commons-codec', version:'1.10' - compile group: 'commons-io', name: 'commons-io', version:'2.5' - compile group: 'org.apache.commons', name: 'commons-lang3', version:'3.4' - compile group: 'redis.clients', name: 'jedis', version:'2.9.0' - testCompile group: 'ch.qos.logback', name: 'logback-classic', version:'1.1.2' + compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.10' + compile group: 'org.apache.httpcomponents', name: 'httpmime', version: '4.5' + compile group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5' + compile group: 'com.google.code.gson', name: 'gson', version: '2.7' + compile group: 'com.google.guava', name: 'guava', version: '19.0' + compile group: 'commons-codec', name: 'commons-codec', version: '1.10' + compile group: 'commons-io', name: 'commons-io', version: '2.5' + compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.4' + compile group: 'redis.clients', name: 'jedis', version: '2.9.0' + testCompile group: 'ch.qos.logback', name: 'logback-classic', version: '1.1.2' } } diff --git a/pom.xml b/pom.xml index dbe53d12..5fc64559 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,8 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" + xmlns="http://maven.apache.org/POM/4.0.0"> 4.0.0 com.github.binarywang weixin-java-parent diff --git a/weixin-java-common/build.gradle b/weixin-java-common/build.gradle index 71800493..f7f40ba0 100644 --- a/weixin-java-common/build.gradle +++ b/weixin-java-common/build.gradle @@ -1,12 +1,11 @@ - description = 'WeiXin Java Tools - Common' dependencies { - compile group: 'com.thoughtworks.xstream', name: 'xstream', version:'1.4.7' - testCompile group: 'junit', name: 'junit', version:'4.11' - testCompile group: 'org.testng', name: 'testng', version:'6.8.7' - testCompile group: 'org.mockito', name: 'mockito-all', version:'1.9.5' - testCompile group: 'com.google.inject', name: 'guice', version:'3.0' - testCompile group: 'org.eclipse.jetty', name: 'jetty-server', version:'9.3.0.RC0' - testCompile group: 'org.eclipse.jetty', name: 'jetty-servlet', version:'9.3.0.RC0' + compile group: 'com.thoughtworks.xstream', name: 'xstream', version: '1.4.7' + testCompile group: 'junit', name: 'junit', version: '4.11' + testCompile group: 'org.testng', name: 'testng', version: '6.8.7' + testCompile group: 'org.mockito', name: 'mockito-all', version: '1.9.5' + testCompile group: 'com.google.inject', name: 'guice', version: '3.0' + testCompile group: 'org.eclipse.jetty', name: 'jetty-server', version: '9.3.0.RC0' + testCompile group: 'org.eclipse.jetty', name: 'jetty-servlet', version: '9.3.0.RC0' } test.useTestNG() diff --git a/weixin-java-common/pom.xml b/weixin-java-common/pom.xml index 49815e50..a0d5683f 100644 --- a/weixin-java-common/pom.xml +++ b/weixin-java-common/pom.xml @@ -1,7 +1,7 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"> 4.0.0 com.github.binarywang diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/annotation/Required.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/annotation/Required.java index 9ed249da..9370561f 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/annotation/Required.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/annotation/Required.java @@ -7,13 +7,13 @@ import java.lang.annotation.Target; /** * 标识某个字段是否是必填的 - * + *

* Created by Binary Wang on 2016/9/25. - * @author binarywang (https://github.com/binarywang) * + * @author binarywang (https://github.com/binarywang) */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Required { -} \ No newline at end of file +} diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/result/WxMediaUploadResult.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/result/WxMediaUploadResult.java index 09901c3e..8ea6a314 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/result/WxMediaUploadResult.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/result/WxMediaUploadResult.java @@ -51,7 +51,7 @@ public class WxMediaUploadResult implements Serializable { @Override public String toString() { return "WxUploadResult [type=" + this.type + ", media_id=" + this.mediaId + ", thumb_media_id=" + this.thumbMediaId - + ", created_at=" + this.createdAt + "]"; + + ", created_at=" + this.createdAt + "]"; } } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/StandardSessionManager.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/StandardSessionManager.java index 7e6c95a2..f20fd5c2 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/StandardSessionManager.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/StandardSessionManager.java @@ -14,7 +14,7 @@ import java.util.concurrent.atomic.AtomicBoolean; public class StandardSessionManager implements WxSessionManager, InternalSessionManager { protected static final StringManager sm = - StringManager.getManager(Constants.Package); + StringManager.getManager(Constants.Package); /** * The descriptive name of this Manager implementation (for logging). */ @@ -82,7 +82,7 @@ public class StandardSessionManager implements WxSessionManager, InternalSession public WxSession getSession(String sessionId, boolean create) { if (sessionId == null) { throw new IllegalStateException - (sm.getString("sessionManagerImpl.getSession.ise")); + (sm.getString("sessionManagerImpl.getSession.ise")); } InternalSession session = findSession(sessionId); @@ -135,15 +135,15 @@ public class StandardSessionManager implements WxSessionManager, InternalSession public InternalSession createSession(String sessionId) { if (sessionId == null) { throw new IllegalStateException - (sm.getString("sessionManagerImpl.createSession.ise")); + (sm.getString("sessionManagerImpl.createSession.ise")); } if ((this.maxActiveSessions >= 0) && - (getActiveSessions() >= this.maxActiveSessions)) { + (getActiveSessions() >= this.maxActiveSessions)) { this.rejectedSessions++; throw new TooManyActiveSessionsException( - sm.getString("sessionManagerImpl.createSession.tmase"), - this.maxActiveSessions); + sm.getString("sessionManagerImpl.createSession.tmase"), + this.maxActiveSessions); } // Recycle or create a Session instance diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/TooManyActiveSessionsException.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/TooManyActiveSessionsException.java index 72a2b4c4..fa1b45fa 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/TooManyActiveSessionsException.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/TooManyActiveSessionsException.java @@ -21,7 +21,7 @@ package me.chanjar.weixin.common.session; * reached and the server is refusing to create any new sessions. */ public class TooManyActiveSessionsException - extends IllegalStateException { + extends IllegalStateException { private static final long serialVersionUID = 1L; /** diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/ToStringUtils.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/ToStringUtils.java index 0fa38391..333e484a 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/ToStringUtils.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/ToStringUtils.java @@ -13,25 +13,10 @@ import org.apache.commons.lang3.builder.ToStringStyle; */ public class ToStringUtils { public static final ToStringStyle THE_STYLE = new SimpleMultiLineToStringStyle(); - private static class SimpleMultiLineToStringStyle extends ToStringStyle { - private static final long serialVersionUID = 4645306494220335355L; - private static final String LINE_SEPARATOR = "\n"; - private static final String NULL_TEXT = ""; - - public SimpleMultiLineToStringStyle() { - super(); - this.setContentStart("["); - this.setFieldSeparator(LINE_SEPARATOR + " "); - this.setFieldSeparatorAtStart(true); - this.setContentEnd(LINE_SEPARATOR + "]"); - this.setNullText(NULL_TEXT); - this.setUseShortClassName(true); - this.setUseIdentityHashCode(false); - } - } /** * 用于产生去掉空值属性并以换行符分割各属性键值的toString字符串 + * * @param obj */ public static String toSimpleString(Object obj) { @@ -58,4 +43,21 @@ public class ToStringUtils { return result.deleteCharAt(result.length() - 1).toString(); } + + private static class SimpleMultiLineToStringStyle extends ToStringStyle { + private static final long serialVersionUID = 4645306494220335355L; + private static final String LINE_SEPARATOR = "\n"; + private static final String NULL_TEXT = ""; + + public SimpleMultiLineToStringStyle() { + super(); + this.setContentStart("["); + this.setFieldSeparator(LINE_SEPARATOR + " "); + this.setFieldSeparatorAtStart(true); + this.setContentEnd(LINE_SEPARATOR + "]"); + this.setNullText(NULL_TEXT); + this.setUseShortClassName(true); + this.setUseIdentityHashCode(false); + } + } } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/SHA1.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/SHA1.java index 683f2ecf..36aa1e7e 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/SHA1.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/SHA1.java @@ -1,9 +1,9 @@ package me.chanjar.weixin.common.util.crypto; -import java.util.Arrays; - import org.apache.commons.codec.digest.DigestUtils; +import java.util.Arrays; + /** * Created by Daniel Qian on 14/10/19. */ diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/WxCryptUtil.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/WxCryptUtil.java index a809fe3b..68834f9e 100755 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/WxCryptUtil.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/WxCryptUtil.java @@ -6,6 +6,10 @@ * 针对org.apache.commons.codec.binary.Base64, * 需要导入架包commons-codec-1.9(或commons-codec-1.8等其他版本) * 官方下载地址:http://commons.apache.org/proper/commons-codec/download_codec.cgi + *

+ * 针对org.apache.commons.codec.binary.Base64, + * 需要导入架包commons-codec-1.9(或commons-codec-1.8等其他版本) + * 官方下载地址:http://commons.apache.org/proper/commons-codec/download_codec.cgi */ // ------------------------------------------------------------------------ @@ -17,10 +21,10 @@ */ package me.chanjar.weixin.common.util.crypto; -import java.io.StringReader; -import java.nio.charset.Charset; -import java.util.Arrays; -import java.util.Random; +import org.apache.commons.codec.binary.Base64; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.InputSource; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; @@ -28,11 +32,10 @@ import javax.crypto.spec.SecretKeySpec; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; - -import org.apache.commons.codec.binary.Base64; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.xml.sax.InputSource; +import java.io.StringReader; +import java.nio.charset.Charset; +import java.util.Arrays; +import java.util.Random; public class WxCryptUtil { @@ -84,6 +87,66 @@ public class WxCryptUtil { } } + /** + * 将一个数字转换成生成4个字节的网络字节序bytes数组 + * + * @param number + */ + private static byte[] number2BytesInNetworkOrder(int number) { + byte[] orderBytes = new byte[4]; + orderBytes[3] = (byte) (number & 0xFF); + orderBytes[2] = (byte) (number >> 8 & 0xFF); + orderBytes[1] = (byte) (number >> 16 & 0xFF); + orderBytes[0] = (byte) (number >> 24 & 0xFF); + return orderBytes; + } + + /** + * 4个字节的网络字节序bytes数组还原成一个数字 + * + * @param bytesInNetworkOrder + */ + private static int bytesNetworkOrder2Number(byte[] bytesInNetworkOrder) { + int sourceNumber = 0; + for (int i = 0; i < 4; i++) { + sourceNumber <<= 8; + sourceNumber |= bytesInNetworkOrder[i] & 0xff; + } + return sourceNumber; + } + + /** + * 随机生成16位字符串 + */ + private static String genRandomStr() { + String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + Random random = new Random(); + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < 16; i++) { + int number = random.nextInt(base.length()); + sb.append(base.charAt(number)); + } + return sb.toString(); + } + + /** + * 生成xml消息 + * + * @param encrypt 加密后的消息密文 + * @param signature 安全签名 + * @param timestamp 时间戳 + * @param nonce 随机字符串 + * @return 生成的xml字符串 + */ + private static String generateXml(String encrypt, String signature, + String timestamp, String nonce) { + String format = "\n" + "\n" + + "\n" + + "%3$s\n" + "\n" + + ""; + return String.format(format, encrypt, signature, timestamp, nonce); + } + /** * 将公众平台回复用户的消息加密打包. *

    @@ -119,7 +182,7 @@ public class WxCryptUtil { byte[] randomStringBytes = randomStr.getBytes(CHARSET); byte[] plainTextBytes = plainText.getBytes(CHARSET); byte[] bytesOfSizeInNetworkOrder = number2BytesInNetworkOrder( - plainTextBytes.length); + plainTextBytes.length); byte[] appIdBytes = this.appidOrCorpid.getBytes(CHARSET); // randomStr + networkBytesOrder + text + appid @@ -198,7 +261,7 @@ public class WxCryptUtil { Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); SecretKeySpec key_spec = new SecretKeySpec(this.aesKey, "AES"); IvParameterSpec iv = new IvParameterSpec( - Arrays.copyOfRange(this.aesKey, 0, 16)); + Arrays.copyOfRange(this.aesKey, 0, 16)); cipher.init(Cipher.DECRYPT_MODE, key_spec, iv); // 使用BASE64对密文进行解码 @@ -221,9 +284,9 @@ public class WxCryptUtil { int xmlLength = bytesNetworkOrder2Number(networkOrder); xmlContent = new String(Arrays.copyOfRange(bytes, 20, 20 + xmlLength), - CHARSET); + CHARSET); from_appid = new String( - Arrays.copyOfRange(bytes, 20 + xmlLength, bytes.length), CHARSET); + Arrays.copyOfRange(bytes, 20 + xmlLength, bytes.length), CHARSET); } catch (Exception e) { throw new RuntimeException(e); } @@ -237,64 +300,4 @@ public class WxCryptUtil { } - /** - * 将一个数字转换成生成4个字节的网络字节序bytes数组 - * - * @param number - */ - private static byte[] number2BytesInNetworkOrder(int number) { - byte[] orderBytes = new byte[4]; - orderBytes[3] = (byte) (number & 0xFF); - orderBytes[2] = (byte) (number >> 8 & 0xFF); - orderBytes[1] = (byte) (number >> 16 & 0xFF); - orderBytes[0] = (byte) (number >> 24 & 0xFF); - return orderBytes; - } - - /** - * 4个字节的网络字节序bytes数组还原成一个数字 - * - * @param bytesInNetworkOrder - */ - private static int bytesNetworkOrder2Number(byte[] bytesInNetworkOrder) { - int sourceNumber = 0; - for (int i = 0; i < 4; i++) { - sourceNumber <<= 8; - sourceNumber |= bytesInNetworkOrder[i] & 0xff; - } - return sourceNumber; - } - - /** - * 随机生成16位字符串 - */ - private static String genRandomStr() { - String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; - Random random = new Random(); - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < 16; i++) { - int number = random.nextInt(base.length()); - sb.append(base.charAt(number)); - } - return sb.toString(); - } - - /** - * 生成xml消息 - * - * @param encrypt 加密后的消息密文 - * @param signature 安全签名 - * @param timestamp 时间戳 - * @param nonce 随机字符串 - * @return 生成的xml字符串 - */ - private static String generateXml(String encrypt, String signature, - String timestamp, String nonce) { - String format = "\n" + "\n" - + "\n" - + "%3$s\n" + "\n" - + ""; - return String.format(format, encrypt, signature, timestamp, nonce); - } - } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/fs/FileUtils.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/fs/FileUtils.java index 9ff25ebc..df031b33 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/fs/FileUtils.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/fs/FileUtils.java @@ -25,7 +25,7 @@ public class FileUtils { } tmpFile.deleteOnExit(); - + try (FileOutputStream fos = new FileOutputStream(tmpFile)) { int read = 0; byte[] bytes = new byte[1024 * 100]; @@ -35,7 +35,7 @@ public class FileUtils { fos.flush(); return tmpFile; - } + } } /** diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MediaDownloadRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MediaDownloadRequestExecutor.java index 8ea7658d..72ceeb14 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MediaDownloadRequestExecutor.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MediaDownloadRequestExecutor.java @@ -1,38 +1,10 @@ package me.chanjar.weixin.common.util.http; -import jodd.http.HttpConnectionProvider; -import jodd.http.HttpRequest; -import jodd.http.HttpResponse; -import jodd.http.ProxyInfo; -import me.chanjar.weixin.common.bean.result.WxError; -import me.chanjar.weixin.common.bean.result.WxMediaUploadResult; -import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.common.util.fs.FileUtils; import me.chanjar.weixin.common.util.http.apache.ApacheMediaDownloadRequestExecutor; -import me.chanjar.weixin.common.util.http.apache.InputStreamResponseHandler; -import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; import me.chanjar.weixin.common.util.http.jodd.JoddMediaDownloadRequestExecutor; import me.chanjar.weixin.common.util.http.okhttp.OkMediaDownloadRequestExecutor; -import me.chanjar.weixin.common.util.http.okhttp.OkhttpProxyInfo; -import okhttp3.*; -import org.apache.commons.lang3.StringUtils; -import org.apache.http.Header; -import org.apache.http.HttpHost; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.entity.ContentType; -import org.apache.http.impl.client.CloseableHttpClient; - -import java.io.ByteArrayInputStream; import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.InetSocketAddress; -import java.net.Proxy; -import java.util.regex.Matcher; -import java.util.regex.Pattern; /** * 下载媒体文件请求执行器,请求的参数是String, 返回的结果是File @@ -42,8 +14,14 @@ import java.util.regex.Pattern; */ public abstract class MediaDownloadRequestExecutor implements RequestExecutor { - public static RequestExecutor create(RequestHttp requestHttp, File tmpDirFile){ - switch (requestHttp.getRequestType()){ + protected RequestHttp requestHttp; + protected File tmpDirFile; + public MediaDownloadRequestExecutor(RequestHttp requestHttp, File tmpDirFile) { + this.tmpDirFile = tmpDirFile; + } + + public static RequestExecutor create(RequestHttp requestHttp, File tmpDirFile) { + switch (requestHttp.getRequestType()) { case apacheHttp: return new ApacheMediaDownloadRequestExecutor(requestHttp, tmpDirFile); case joddHttp: @@ -55,11 +33,4 @@ public abstract class MediaDownloadRequestExecutor implements RequestExecu } } - protected RequestHttp requestHttp; - protected File tmpDirFile; - - public MediaDownloadRequestExecutor(RequestHttp requestHttp, File tmpDirFile) { - this.tmpDirFile = tmpDirFile; - } - } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MediaUploadRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MediaUploadRequestExecutor.java index abe3dbd6..1352954c 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MediaUploadRequestExecutor.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MediaUploadRequestExecutor.java @@ -1,34 +1,11 @@ package me.chanjar.weixin.common.util.http; -import jodd.http.HttpConnectionProvider; -import jodd.http.HttpRequest; -import jodd.http.HttpResponse; -import jodd.http.ProxyInfo; -import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.bean.result.WxMediaUploadResult; -import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.common.util.http.apache.ApacheMediaUploadRequestExecutor; -import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; - import me.chanjar.weixin.common.util.http.jodd.JoddMediaUploadRequestExecutor; import me.chanjar.weixin.common.util.http.okhttp.OkMediaUploadRequestExecutor; -import me.chanjar.weixin.common.util.http.okhttp.OkhttpProxyInfo; -import okhttp3.*; - -import org.apache.http.HttpEntity; -import org.apache.http.HttpHost; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.mime.HttpMultipartMode; -import org.apache.http.entity.mime.MultipartEntityBuilder; -import org.apache.http.impl.client.CloseableHttpClient; import java.io.File; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.Proxy; /** * 上传媒体文件请求执行器,请求的参数是File, 返回的结果是String @@ -36,14 +13,14 @@ import java.net.Proxy; * @author Daniel Qian */ public abstract class MediaUploadRequestExecutor implements RequestExecutor { - protected RequestHttp requestHttp; + protected RequestHttp requestHttp; - public MediaUploadRequestExecutor(RequestHttp requestHttp){ - this.requestHttp =requestHttp; + public MediaUploadRequestExecutor(RequestHttp requestHttp) { + this.requestHttp = requestHttp; } - public static RequestExecutor create(RequestHttp requestHttp){ - switch (requestHttp.getRequestType()){ + public static RequestExecutor create(RequestHttp requestHttp) { + switch (requestHttp.getRequestType()) { case apacheHttp: return new ApacheMediaUploadRequestExecutor(requestHttp); case joddHttp: diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/RequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/RequestExecutor.java index b58249e9..a31796e6 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/RequestExecutor.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/RequestExecutor.java @@ -1,17 +1,9 @@ package me.chanjar.weixin.common.util.http; -import jodd.http.HttpConnectionProvider; -import jodd.http.ProxyInfo; import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.common.util.http.okhttp.OkhttpProxyInfo; -import okhttp3.ConnectionPool; - import java.io.IOException; -import org.apache.http.HttpHost; -import org.apache.http.impl.client.CloseableHttpClient; - /** * http请求执行器 * @@ -41,15 +33,15 @@ public interface RequestExecutor { T executeApache(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, E data) throws WxErrorException, IOException; *//** - * jodd-http实现方式 - * @param provider - * @param proxyInfo - * @param uri - * @param data - * @return - * @throws WxErrorException - * @throws IOException - *//* + * jodd-http实现方式 + * @param provider + * @param proxyInfo + * @param uri + * @param data + * @return + * @throws WxErrorException + * @throws IOException + *//* T executeJodd(HttpConnectionProvider provider, ProxyInfo proxyInfo, String uri, E data) throws WxErrorException, IOException; diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/RequestHttp.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/RequestHttp.java index 13eaf939..df27d44e 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/RequestHttp.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/RequestHttp.java @@ -3,22 +3,23 @@ package me.chanjar.weixin.common.util.http; /** * Created by ecoolper on 2017/4/22. */ -public interface RequestHttp { +public interface RequestHttp { /** * 返回httpClient + * * @return */ H getRequestHttpClient(); /** * 返回httpProxy + * * @return */ P getRequestHttpProxy(); /** - * * @return */ HttpType getRequestType(); diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimpleGetRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimpleGetRequestExecutor.java index ec7a2e57..c7d782f5 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimpleGetRequestExecutor.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimpleGetRequestExecutor.java @@ -1,29 +1,8 @@ package me.chanjar.weixin.common.util.http; -import jodd.http.HttpConnectionProvider; -import jodd.http.HttpRequest; -import jodd.http.HttpResponse; -import jodd.http.ProxyInfo; -import me.chanjar.weixin.common.bean.result.WxError; -import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.common.util.http.apache.ApacheSimpleGetRequestExecutor; -import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; - import me.chanjar.weixin.common.util.http.jodd.JoddSimpleGetRequestExecutor; import me.chanjar.weixin.common.util.http.okhttp.OkSimpleGetRequestExecutor; -import me.chanjar.weixin.common.util.http.okhttp.OkhttpProxyInfo; -import okhttp3.*; - -import org.apache.http.HttpHost; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.Proxy; -import java.util.concurrent.TimeUnit; /** * 简单的GET请求执行器,请求的参数是String, 返回的结果也是String @@ -31,15 +10,15 @@ import java.util.concurrent.TimeUnit; * @author Daniel Qian */ public abstract class SimpleGetRequestExecutor implements RequestExecutor { - protected RequestHttp requestHttp; + protected RequestHttp requestHttp; - public SimpleGetRequestExecutor(RequestHttp requestHttp){ - this.requestHttp =requestHttp; + public SimpleGetRequestExecutor(RequestHttp requestHttp) { + this.requestHttp = requestHttp; } - public static RequestExecutor create(RequestHttp requestHttp){ - switch(requestHttp.getRequestType()){ + public static RequestExecutor create(RequestHttp requestHttp) { + switch (requestHttp.getRequestType()) { case apacheHttp: return new ApacheSimpleGetRequestExecutor(requestHttp); case joddHttp: diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimplePostRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimplePostRequestExecutor.java index c6f4e6a7..a8d4d783 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimplePostRequestExecutor.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimplePostRequestExecutor.java @@ -1,29 +1,8 @@ package me.chanjar.weixin.common.util.http; -import jodd.http.HttpConnectionProvider; -import jodd.http.HttpRequest; -import jodd.http.HttpResponse; -import jodd.http.ProxyInfo; -import me.chanjar.weixin.common.bean.result.WxError; -import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.common.util.http.apache.ApacheSimpleGetRequestExecutor; import me.chanjar.weixin.common.util.http.apache.ApacheSimplePostRequestExecutor; -import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; - import me.chanjar.weixin.common.util.http.jodd.JoddSimplePostRequestExecutor; import me.chanjar.weixin.common.util.http.okhttp.OkSimplePostRequestExecutor; -import me.chanjar.weixin.common.util.http.okhttp.OkhttpProxyInfo; -import okhttp3.*; - -import org.apache.http.Consts; -import org.apache.http.HttpHost; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; - -import java.io.IOException; /** * 用装饰模式实现 @@ -32,14 +11,14 @@ import java.io.IOException; * @author Daniel Qian */ public abstract class SimplePostRequestExecutor implements RequestExecutor { - protected RequestHttp requestHttp; + protected RequestHttp requestHttp; - public SimplePostRequestExecutor(RequestHttp requestHttp){ - this.requestHttp =requestHttp; + public SimplePostRequestExecutor(RequestHttp requestHttp) { + this.requestHttp = requestHttp; } - public static RequestExecutor create(RequestHttp requestHttp){ - switch (requestHttp.getRequestType()){ + public static RequestExecutor create(RequestHttp requestHttp) { + switch (requestHttp.getRequestType()) { case apacheHttp: return new ApacheSimplePostRequestExecutor(requestHttp); case joddHttp: diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/WxDnsResolver.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/WxDnsResolver.java index 315bf6f6..6c613708 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/WxDnsResolver.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/WxDnsResolver.java @@ -1,64 +1,61 @@ package me.chanjar.weixin.common.util.http; +import org.apache.http.conn.DnsResolver; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.net.InetAddress; import java.net.UnknownHostException; import java.util.HashMap; import java.util.Map; -import org.apache.http.conn.DnsResolver; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * 微信DNS域名解析器,将微信域名绑定到指定IP * -------------------------------------------- * 适用于服务器端调用微信服务器需要开通出口防火墙情况 - * + *

    * Created by Andy Huo on 17/03/28. */ public class WxDnsResolver implements DnsResolver { - - protected final Logger log = LoggerFactory.getLogger(WxDnsResolver.class); - - private static Map MAPPINGS = new HashMap(); - - private final static String WECHAT_API_URL = "api.weixin.qq.com"; - - private String wxApiIp; - - public WxDnsResolver(String ip){ - - this.wxApiIp = ip; - this.init(); - } - - private void init(){ - if(log.isDebugEnabled()){ - log.debug("init wechat dns config with ip {}", wxApiIp); - } - try { - MAPPINGS.put(WECHAT_API_URL, new InetAddress[]{InetAddress.getByName(wxApiIp)}); - } catch (UnknownHostException e) { - //如果初始化DNS配置失败则使用默认配置,不影响服务的启动 - log.error("init WxDnsResolver error", e); - MAPPINGS = new HashMap(); - } - - } - @Override - public InetAddress[] resolve(String host) throws UnknownHostException { - - - return MAPPINGS.containsKey(host) ? MAPPINGS.get(host) : new InetAddress[0]; - } + private final static String WECHAT_API_URL = "api.weixin.qq.com"; + private static Map MAPPINGS = new HashMap(); + protected final Logger log = LoggerFactory.getLogger(WxDnsResolver.class); + private String wxApiIp; + + public WxDnsResolver(String ip) { + + this.wxApiIp = ip; + this.init(); + } + + private void init() { + if (log.isDebugEnabled()) { + log.debug("init wechat dns config with ip {}", wxApiIp); + } + try { + MAPPINGS.put(WECHAT_API_URL, new InetAddress[]{InetAddress.getByName(wxApiIp)}); + } catch (UnknownHostException e) { + //如果初始化DNS配置失败则使用默认配置,不影响服务的启动 + log.error("init WxDnsResolver error", e); + MAPPINGS = new HashMap(); + } + + } + + @Override + public InetAddress[] resolve(String host) throws UnknownHostException { + + + return MAPPINGS.containsKey(host) ? MAPPINGS.get(host) : new InetAddress[0]; + } - public String getWxApiIp() { - return wxApiIp; - } + public String getWxApiIp() { + return wxApiIp; + } - public void setWxApiIp(String wxApiIp) { - this.wxApiIp = wxApiIp; - this.init(); - } + public void setWxApiIp(String wxApiIp) { + this.wxApiIp = wxApiIp; + this.init(); + } } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheHttpClientBuilder.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheHttpClientBuilder.java index 87a86dba..939b6247 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheHttpClientBuilder.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheHttpClientBuilder.java @@ -5,6 +5,7 @@ import org.apache.http.impl.client.CloseableHttpClient; /** * httpclient build interface + * * @author kakotor */ public interface ApacheHttpClientBuilder { diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheHttpDnsClientBuilder.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheHttpDnsClientBuilder.java index 6f069822..d3e5a1c1 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheHttpDnsClientBuilder.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheHttpDnsClientBuilder.java @@ -30,285 +30,277 @@ import java.util.concurrent.atomic.AtomicBoolean; /** * httpclient 连接管理器 自带DNS解析 - * + *

    * 大部分代码拷贝自:DefaultApacheHttpClientBuilder * * @author Andy.Huo */ @NotThreadSafe public class ApacheHttpDnsClientBuilder implements ApacheHttpClientBuilder { - protected final Logger log = LoggerFactory.getLogger(ApacheHttpDnsClientBuilder.class); - private final AtomicBoolean prepared = new AtomicBoolean(false); - private int connectionRequestTimeout = 3000; - private int connectionTimeout = 5000; - private int soTimeout = 5000; - private int idleConnTimeout = 60000; - private int checkWaitTime = 60000; - private int maxConnPerHost = 10; - private int maxTotalConn = 50; - private String userAgent; - - private DnsResolver dnsResover; - - private HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() { - @Override - public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { - return false; - } - }; - private SSLConnectionSocketFactory sslConnectionSocketFactory = SSLConnectionSocketFactory.getSocketFactory(); - private PlainConnectionSocketFactory plainConnectionSocketFactory = PlainConnectionSocketFactory.getSocketFactory(); - private String httpProxyHost; - private int httpProxyPort; - private String httpProxyUsername; - private String httpProxyPassword; - - /** - * 闲置连接监控线程 - */ - private IdleConnectionMonitorThread idleConnectionMonitorThread; - private HttpClientBuilder httpClientBuilder; - - private ApacheHttpDnsClientBuilder() { - } - - public static ApacheHttpDnsClientBuilder get() { - return new ApacheHttpDnsClientBuilder(); - } - - @Override - public ApacheHttpClientBuilder httpProxyHost(String httpProxyHost) { - this.httpProxyHost = httpProxyHost; - return this; - } - - @Override - public ApacheHttpClientBuilder httpProxyPort(int httpProxyPort) { - this.httpProxyPort = httpProxyPort; - return this; - } - - @Override - public ApacheHttpClientBuilder httpProxyUsername(String httpProxyUsername) { - this.httpProxyUsername = httpProxyUsername; - return this; - } - - @Override - public ApacheHttpClientBuilder httpProxyPassword(String httpProxyPassword) { - this.httpProxyPassword = httpProxyPassword; - return this; - } - - @Override - public ApacheHttpClientBuilder sslConnectionSocketFactory(SSLConnectionSocketFactory sslConnectionSocketFactory) { - this.sslConnectionSocketFactory = sslConnectionSocketFactory; - return this; - } - - /** - * 获取链接的超时时间设置,默认3000ms - *

    - * 设置为零时不超时,一直等待. 设置为负数是使用系统默认设置(非上述的3000ms的默认值,而是httpclient的默认设置). - *

    - * - * @param connectionRequestTimeout - * 获取链接的超时时间设置(单位毫秒),默认3000ms - */ - public void setConnectionRequestTimeout(int connectionRequestTimeout) { - this.connectionRequestTimeout = connectionRequestTimeout; - } - - /** - * 建立链接的超时时间,默认为5000ms.由于是在链接池获取链接,此设置应该并不起什么作用 - *

    - * 设置为零时不超时,一直等待. 设置为负数是使用系统默认设置(非上述的5000ms的默认值,而是httpclient的默认设置). - *

    - * - * @param connectionTimeout - * 建立链接的超时时间设置(单位毫秒),默认5000ms - */ - public void setConnectionTimeout(int connectionTimeout) { - this.connectionTimeout = connectionTimeout; - } - - /** - * 默认NIO的socket超时设置,默认5000ms. - * - * @param soTimeout - * 默认NIO的socket超时设置,默认5000ms. - * @see java.net.SocketOptions#SO_TIMEOUT - */ - public void setSoTimeout(int soTimeout) { - this.soTimeout = soTimeout; - } - - /** - * 空闲链接的超时时间,默认60000ms. - *

    - * 超时的链接将在下一次空闲链接检查是被销毁 - *

    - * - * @param idleConnTimeout - * 空闲链接的超时时间,默认60000ms. - */ - public void setIdleConnTimeout(int idleConnTimeout) { - this.idleConnTimeout = idleConnTimeout; - } - - /** - * 检查空间链接的间隔周期,默认60000ms. - * - * @param checkWaitTime - * 检查空间链接的间隔周期,默认60000ms. - */ - public void setCheckWaitTime(int checkWaitTime) { - this.checkWaitTime = checkWaitTime; - } - - /** - * 每路的最大链接数,默认10 - * - * @param maxConnPerHost - * 每路的最大链接数,默认10 - */ - public void setMaxConnPerHost(int maxConnPerHost) { - this.maxConnPerHost = maxConnPerHost; - } - - /** - * 最大总连接数,默认50 - * - * @param maxTotalConn - * 最大总连接数,默认50 - */ - public void setMaxTotalConn(int maxTotalConn) { - this.maxTotalConn = maxTotalConn; - } - - /** - * 自定义httpclient的User Agent - * - * @param userAgent - * User Agent - */ - public void setUserAgent(String userAgent) { - this.userAgent = userAgent; - } - - public IdleConnectionMonitorThread getIdleConnectionMonitorThread() { - return this.idleConnectionMonitorThread; - } - - private synchronized void prepare() { - if (prepared.get()) { - return; - } - Registry registry = RegistryBuilder.create() - .register("http", this.plainConnectionSocketFactory).register("https", this.sslConnectionSocketFactory) - .build(); - - @SuppressWarnings("resource") - PoolingHttpClientConnectionManager connectionManager; - if(dnsResover != null){ - if(log.isDebugEnabled()){ - log.debug("specified dns resolver."); - } - connectionManager = new PoolingHttpClientConnectionManager(registry, dnsResover); - }else{ - if(log.isDebugEnabled()){ - log.debug("Not specified dns resolver."); - } - connectionManager = new PoolingHttpClientConnectionManager(registry); - } - - connectionManager.setMaxTotal(this.maxTotalConn); - connectionManager.setDefaultMaxPerRoute(this.maxConnPerHost); - connectionManager - .setDefaultSocketConfig(SocketConfig.copy(SocketConfig.DEFAULT).setSoTimeout(this.soTimeout).build()); - - this.idleConnectionMonitorThread = new IdleConnectionMonitorThread(connectionManager, this.idleConnTimeout, - this.checkWaitTime); - this.idleConnectionMonitorThread.setDaemon(true); - this.idleConnectionMonitorThread.start(); - - this.httpClientBuilder = HttpClients.custom().setConnectionManager(connectionManager) - .setConnectionManagerShared(true) - .setDefaultRequestConfig(RequestConfig.custom().setSocketTimeout(this.soTimeout) - .setConnectTimeout(this.connectionTimeout) - .setConnectionRequestTimeout(this.connectionRequestTimeout).build()) - .setRetryHandler(this.httpRequestRetryHandler); - - if (StringUtils.isNotBlank(this.httpProxyHost) && StringUtils.isNotBlank(this.httpProxyUsername)) { - // 使用代理服务器 需要用户认证的代理服务器 - CredentialsProvider provider = new BasicCredentialsProvider(); - provider.setCredentials(new AuthScope(this.httpProxyHost, this.httpProxyPort), - new UsernamePasswordCredentials(this.httpProxyUsername, this.httpProxyPassword)); - this.httpClientBuilder.setDefaultCredentialsProvider(provider); - } - - if (StringUtils.isNotBlank(this.userAgent)) { - this.httpClientBuilder.setUserAgent(this.userAgent); - } - prepared.set(true); - } - - @Override - public CloseableHttpClient build() { - if (!prepared.get()) { - prepare(); - } - return this.httpClientBuilder.build(); - } - - public static class IdleConnectionMonitorThread extends Thread { - private final HttpClientConnectionManager connMgr; - private final int idleConnTimeout; - private final int checkWaitTime; - private volatile boolean shutdown; - - public IdleConnectionMonitorThread(HttpClientConnectionManager connMgr, int idleConnTimeout, - int checkWaitTime) { - super("IdleConnectionMonitorThread"); - this.connMgr = connMgr; - this.idleConnTimeout = idleConnTimeout; - this.checkWaitTime = checkWaitTime; - } - - @Override - public void run() { - try { - while (!this.shutdown) { - synchronized (this) { - wait(this.checkWaitTime); - this.connMgr.closeExpiredConnections(); - this.connMgr.closeIdleConnections(this.idleConnTimeout, TimeUnit.MILLISECONDS); - } - } - } catch (InterruptedException ignore) { - } - } - - public void trigger() { - synchronized (this) { - notifyAll(); - } - } - - public void shutdown() { - this.shutdown = true; - synchronized (this) { - notifyAll(); - } - } - } - - public DnsResolver getDnsResover() { - return dnsResover; - } - - public void setDnsResover(DnsResolver dnsResover) { - this.dnsResover = dnsResover; - } + protected final Logger log = LoggerFactory.getLogger(ApacheHttpDnsClientBuilder.class); + private final AtomicBoolean prepared = new AtomicBoolean(false); + private int connectionRequestTimeout = 3000; + private int connectionTimeout = 5000; + private int soTimeout = 5000; + private int idleConnTimeout = 60000; + private int checkWaitTime = 60000; + private int maxConnPerHost = 10; + private int maxTotalConn = 50; + private String userAgent; + + private DnsResolver dnsResover; + + private HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() { + @Override + public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { + return false; + } + }; + private SSLConnectionSocketFactory sslConnectionSocketFactory = SSLConnectionSocketFactory.getSocketFactory(); + private PlainConnectionSocketFactory plainConnectionSocketFactory = PlainConnectionSocketFactory.getSocketFactory(); + private String httpProxyHost; + private int httpProxyPort; + private String httpProxyUsername; + private String httpProxyPassword; + + /** + * 闲置连接监控线程 + */ + private IdleConnectionMonitorThread idleConnectionMonitorThread; + private HttpClientBuilder httpClientBuilder; + + private ApacheHttpDnsClientBuilder() { + } + + public static ApacheHttpDnsClientBuilder get() { + return new ApacheHttpDnsClientBuilder(); + } + + @Override + public ApacheHttpClientBuilder httpProxyHost(String httpProxyHost) { + this.httpProxyHost = httpProxyHost; + return this; + } + + @Override + public ApacheHttpClientBuilder httpProxyPort(int httpProxyPort) { + this.httpProxyPort = httpProxyPort; + return this; + } + + @Override + public ApacheHttpClientBuilder httpProxyUsername(String httpProxyUsername) { + this.httpProxyUsername = httpProxyUsername; + return this; + } + + @Override + public ApacheHttpClientBuilder httpProxyPassword(String httpProxyPassword) { + this.httpProxyPassword = httpProxyPassword; + return this; + } + + @Override + public ApacheHttpClientBuilder sslConnectionSocketFactory(SSLConnectionSocketFactory sslConnectionSocketFactory) { + this.sslConnectionSocketFactory = sslConnectionSocketFactory; + return this; + } + + /** + * 获取链接的超时时间设置,默认3000ms + *

    + * 设置为零时不超时,一直等待. 设置为负数是使用系统默认设置(非上述的3000ms的默认值,而是httpclient的默认设置). + *

    + * + * @param connectionRequestTimeout 获取链接的超时时间设置(单位毫秒),默认3000ms + */ + public void setConnectionRequestTimeout(int connectionRequestTimeout) { + this.connectionRequestTimeout = connectionRequestTimeout; + } + + /** + * 建立链接的超时时间,默认为5000ms.由于是在链接池获取链接,此设置应该并不起什么作用 + *

    + * 设置为零时不超时,一直等待. 设置为负数是使用系统默认设置(非上述的5000ms的默认值,而是httpclient的默认设置). + *

    + * + * @param connectionTimeout 建立链接的超时时间设置(单位毫秒),默认5000ms + */ + public void setConnectionTimeout(int connectionTimeout) { + this.connectionTimeout = connectionTimeout; + } + + /** + * 默认NIO的socket超时设置,默认5000ms. + * + * @param soTimeout 默认NIO的socket超时设置,默认5000ms. + * @see java.net.SocketOptions#SO_TIMEOUT + */ + public void setSoTimeout(int soTimeout) { + this.soTimeout = soTimeout; + } + + /** + * 空闲链接的超时时间,默认60000ms. + *

    + * 超时的链接将在下一次空闲链接检查是被销毁 + *

    + * + * @param idleConnTimeout 空闲链接的超时时间,默认60000ms. + */ + public void setIdleConnTimeout(int idleConnTimeout) { + this.idleConnTimeout = idleConnTimeout; + } + + /** + * 检查空间链接的间隔周期,默认60000ms. + * + * @param checkWaitTime 检查空间链接的间隔周期,默认60000ms. + */ + public void setCheckWaitTime(int checkWaitTime) { + this.checkWaitTime = checkWaitTime; + } + + /** + * 每路的最大链接数,默认10 + * + * @param maxConnPerHost 每路的最大链接数,默认10 + */ + public void setMaxConnPerHost(int maxConnPerHost) { + this.maxConnPerHost = maxConnPerHost; + } + + /** + * 最大总连接数,默认50 + * + * @param maxTotalConn 最大总连接数,默认50 + */ + public void setMaxTotalConn(int maxTotalConn) { + this.maxTotalConn = maxTotalConn; + } + + /** + * 自定义httpclient的User Agent + * + * @param userAgent User Agent + */ + public void setUserAgent(String userAgent) { + this.userAgent = userAgent; + } + + public IdleConnectionMonitorThread getIdleConnectionMonitorThread() { + return this.idleConnectionMonitorThread; + } + + private synchronized void prepare() { + if (prepared.get()) { + return; + } + Registry registry = RegistryBuilder.create() + .register("http", this.plainConnectionSocketFactory).register("https", this.sslConnectionSocketFactory) + .build(); + + @SuppressWarnings("resource") + PoolingHttpClientConnectionManager connectionManager; + if (dnsResover != null) { + if (log.isDebugEnabled()) { + log.debug("specified dns resolver."); + } + connectionManager = new PoolingHttpClientConnectionManager(registry, dnsResover); + } else { + if (log.isDebugEnabled()) { + log.debug("Not specified dns resolver."); + } + connectionManager = new PoolingHttpClientConnectionManager(registry); + } + + connectionManager.setMaxTotal(this.maxTotalConn); + connectionManager.setDefaultMaxPerRoute(this.maxConnPerHost); + connectionManager + .setDefaultSocketConfig(SocketConfig.copy(SocketConfig.DEFAULT).setSoTimeout(this.soTimeout).build()); + + this.idleConnectionMonitorThread = new IdleConnectionMonitorThread(connectionManager, this.idleConnTimeout, + this.checkWaitTime); + this.idleConnectionMonitorThread.setDaemon(true); + this.idleConnectionMonitorThread.start(); + + this.httpClientBuilder = HttpClients.custom().setConnectionManager(connectionManager) + .setConnectionManagerShared(true) + .setDefaultRequestConfig(RequestConfig.custom().setSocketTimeout(this.soTimeout) + .setConnectTimeout(this.connectionTimeout) + .setConnectionRequestTimeout(this.connectionRequestTimeout).build()) + .setRetryHandler(this.httpRequestRetryHandler); + + if (StringUtils.isNotBlank(this.httpProxyHost) && StringUtils.isNotBlank(this.httpProxyUsername)) { + // 使用代理服务器 需要用户认证的代理服务器 + CredentialsProvider provider = new BasicCredentialsProvider(); + provider.setCredentials(new AuthScope(this.httpProxyHost, this.httpProxyPort), + new UsernamePasswordCredentials(this.httpProxyUsername, this.httpProxyPassword)); + this.httpClientBuilder.setDefaultCredentialsProvider(provider); + } + + if (StringUtils.isNotBlank(this.userAgent)) { + this.httpClientBuilder.setUserAgent(this.userAgent); + } + prepared.set(true); + } + + @Override + public CloseableHttpClient build() { + if (!prepared.get()) { + prepare(); + } + return this.httpClientBuilder.build(); + } + + public DnsResolver getDnsResover() { + return dnsResover; + } + + public void setDnsResover(DnsResolver dnsResover) { + this.dnsResover = dnsResover; + } + + public static class IdleConnectionMonitorThread extends Thread { + private final HttpClientConnectionManager connMgr; + private final int idleConnTimeout; + private final int checkWaitTime; + private volatile boolean shutdown; + + public IdleConnectionMonitorThread(HttpClientConnectionManager connMgr, int idleConnTimeout, + int checkWaitTime) { + super("IdleConnectionMonitorThread"); + this.connMgr = connMgr; + this.idleConnTimeout = idleConnTimeout; + this.checkWaitTime = checkWaitTime; + } + + @Override + public void run() { + try { + while (!this.shutdown) { + synchronized (this) { + wait(this.checkWaitTime); + this.connMgr.closeExpiredConnections(); + this.connMgr.closeIdleConnections(this.idleConnTimeout, TimeUnit.MILLISECONDS); + } + } + } catch (InterruptedException ignore) { + } + } + + public void trigger() { + synchronized (this) { + notifyAll(); + } + } + + public void shutdown() { + this.shutdown = true; + synchronized (this) { + notifyAll(); + } + } + } } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheMediaDownloadRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheMediaDownloadRequestExecutor.java index 8546a791..6a928648 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheMediaDownloadRequestExecutor.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheMediaDownloadRequestExecutor.java @@ -1,11 +1,10 @@ package me.chanjar.weixin.common.util.http.apache; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.fs.FileUtils; +import me.chanjar.weixin.common.util.http.MediaDownloadRequestExecutor; +import me.chanjar.weixin.common.util.http.RequestHttp; import org.apache.commons.lang3.StringUtils; import org.apache.http.Header; import org.apache.http.HttpHost; @@ -15,13 +14,11 @@ import org.apache.http.client.methods.HttpGet; import org.apache.http.entity.ContentType; import org.apache.http.impl.client.CloseableHttpClient; -import me.chanjar.weixin.common.bean.result.WxError; -import me.chanjar.weixin.common.bean.result.WxMediaUploadResult; -import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.common.util.fs.FileUtils; -import me.chanjar.weixin.common.util.http.MediaDownloadRequestExecutor; -import me.chanjar.weixin.common.util.http.RequestExecutor; -import me.chanjar.weixin.common.util.http.RequestHttp; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.regex.Matcher; +import java.util.regex.Pattern; /** * Created by ecoolper on 2017/5/5. diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheMediaUploadRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheMediaUploadRequestExecutor.java index a9c10a58..e250157b 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheMediaUploadRequestExecutor.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheMediaUploadRequestExecutor.java @@ -1,8 +1,10 @@ package me.chanjar.weixin.common.util.http.apache; -import java.io.File; -import java.io.IOException; - +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.bean.result.WxMediaUploadResult; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.MediaUploadRequestExecutor; +import me.chanjar.weixin.common.util.http.RequestHttp; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.client.config.RequestConfig; @@ -13,12 +15,8 @@ import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; -import me.chanjar.weixin.common.bean.result.WxError; -import me.chanjar.weixin.common.bean.result.WxMediaUploadResult; -import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.common.util.http.MediaUploadRequestExecutor; -import me.chanjar.weixin.common.util.http.RequestExecutor; -import me.chanjar.weixin.common.util.http.RequestHttp; +import java.io.File; +import java.io.IOException; /** * Created by ecoolper on 2017/5/5. diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheSimpleGetRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheSimpleGetRequestExecutor.java index 9564fd36..ebc7050e 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheSimpleGetRequestExecutor.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheSimpleGetRequestExecutor.java @@ -1,18 +1,16 @@ package me.chanjar.weixin.common.util.http.apache; -import java.io.IOException; - +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.RequestHttp; +import me.chanjar.weixin.common.util.http.SimpleGetRequestExecutor; import org.apache.http.HttpHost; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; -import me.chanjar.weixin.common.bean.result.WxError; -import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.common.util.http.RequestExecutor; -import me.chanjar.weixin.common.util.http.RequestHttp; -import me.chanjar.weixin.common.util.http.SimpleGetRequestExecutor; +import java.io.IOException; /** * Created by ecoolper on 2017/5/4. diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheSimplePostRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheSimplePostRequestExecutor.java index 4e092c43..cc85fa76 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheSimplePostRequestExecutor.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/ApacheSimplePostRequestExecutor.java @@ -1,7 +1,9 @@ package me.chanjar.weixin.common.util.http.apache; -import java.io.IOException; - +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.RequestHttp; +import me.chanjar.weixin.common.util.http.SimplePostRequestExecutor; import org.apache.http.Consts; import org.apache.http.HttpHost; import org.apache.http.client.config.RequestConfig; @@ -10,11 +12,7 @@ import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; -import me.chanjar.weixin.common.bean.result.WxError; -import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.common.util.http.RequestExecutor; -import me.chanjar.weixin.common.util.http.RequestHttp; -import me.chanjar.weixin.common.util.http.SimplePostRequestExecutor; +import java.io.IOException; /** * Created by ecoolper on 2017/5/4. diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/DefaultApacheHttpClientBuilder.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/DefaultApacheHttpClientBuilder.java index 2bb1f072..875f2fcc 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/DefaultApacheHttpClientBuilder.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/apache/DefaultApacheHttpClientBuilder.java @@ -188,7 +188,7 @@ public class DefaultApacheHttpClientBuilder implements ApacheHttpClientBuilder { } private synchronized void prepare() { - if(prepared.get()){ + if (prepared.get()) { return; } Registry registry = RegistryBuilder.create() @@ -242,7 +242,7 @@ public class DefaultApacheHttpClientBuilder implements ApacheHttpClientBuilder { @Override public CloseableHttpClient build() { - if(!prepared.get()){ + if (!prepared.get()) { prepare(); } return this.httpClientBuilder.build(); diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/jodd/JoddMediaDownloadRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/jodd/JoddMediaDownloadRequestExecutor.java index f392f5ac..230b3ca6 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/jodd/JoddMediaDownloadRequestExecutor.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/jodd/JoddMediaDownloadRequestExecutor.java @@ -1,14 +1,5 @@ package me.chanjar.weixin.common.util.http.jodd; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.commons.lang3.StringUtils; - import jodd.http.HttpConnectionProvider; import jodd.http.HttpRequest; import jodd.http.HttpResponse; @@ -17,8 +8,15 @@ import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.common.util.fs.FileUtils; import me.chanjar.weixin.common.util.http.MediaDownloadRequestExecutor; -import me.chanjar.weixin.common.util.http.RequestExecutor; import me.chanjar.weixin.common.util.http.RequestHttp; +import org.apache.commons.lang3.StringUtils; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.regex.Matcher; +import java.util.regex.Pattern; /** * Created by ecoolper on 2017/5/5. diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/jodd/JoddMediaUploadRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/jodd/JoddMediaUploadRequestExecutor.java index 91cae4fc..43f17fbc 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/jodd/JoddMediaUploadRequestExecutor.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/jodd/JoddMediaUploadRequestExecutor.java @@ -1,8 +1,5 @@ package me.chanjar.weixin.common.util.http.jodd; -import java.io.File; -import java.io.IOException; - import jodd.http.HttpConnectionProvider; import jodd.http.HttpRequest; import jodd.http.HttpResponse; @@ -11,9 +8,11 @@ import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.bean.result.WxMediaUploadResult; import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.common.util.http.MediaUploadRequestExecutor; -import me.chanjar.weixin.common.util.http.RequestExecutor; import me.chanjar.weixin.common.util.http.RequestHttp; +import java.io.File; +import java.io.IOException; + /** * Created by ecoolper on 2017/5/5. */ diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/jodd/JoddSimpleGetRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/jodd/JoddSimpleGetRequestExecutor.java index ea44e5a6..a43fe5f2 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/jodd/JoddSimpleGetRequestExecutor.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/jodd/JoddSimpleGetRequestExecutor.java @@ -1,23 +1,15 @@ package me.chanjar.weixin.common.util.http.jodd; -import java.io.IOException; - -import org.apache.http.HttpHost; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; - import jodd.http.HttpConnectionProvider; import jodd.http.HttpRequest; import jodd.http.HttpResponse; import jodd.http.ProxyInfo; import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.common.util.http.RequestExecutor; import me.chanjar.weixin.common.util.http.RequestHttp; import me.chanjar.weixin.common.util.http.SimpleGetRequestExecutor; -import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; + +import java.io.IOException; /** * Created by ecoolper on 2017/5/4. diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/jodd/JoddSimplePostRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/jodd/JoddSimplePostRequestExecutor.java index 59eea7b2..1db0f2af 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/jodd/JoddSimplePostRequestExecutor.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/jodd/JoddSimplePostRequestExecutor.java @@ -1,17 +1,16 @@ package me.chanjar.weixin.common.util.http.jodd; -import java.io.IOException; - import jodd.http.HttpConnectionProvider; import jodd.http.HttpRequest; import jodd.http.HttpResponse; import jodd.http.ProxyInfo; import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.common.util.http.RequestExecutor; import me.chanjar.weixin.common.util.http.RequestHttp; import me.chanjar.weixin.common.util.http.SimplePostRequestExecutor; +import java.io.IOException; + /** * Created by ecoolper on 2017/5/4. */ @@ -24,7 +23,7 @@ public class JoddSimplePostRequestExecutor extends SimplePostRequestExecutor{ +public class OkSimplePostRequestExecutor extends SimplePostRequestExecutor { public OkSimplePostRequestExecutor(RequestHttp requestHttp) { super(requestHttp); } @Override - public String execute(String uri, String postEntity) throws WxErrorException, IOException { - ConnectionPool pool = requestHttp.getRequestHttpClient(); + public String execute(String uri, String postEntity) throws WxErrorException, IOException { + ConnectionPool pool = requestHttp.getRequestHttpClient(); final OkhttpProxyInfo proxyInfo = requestHttp.getRequestHttpProxy(); OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder().connectionPool(pool); diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/okhttp/OkhttpProxyInfo.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/okhttp/OkhttpProxyInfo.java index 73ccdafa..daaa92f2 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/okhttp/OkhttpProxyInfo.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/okhttp/OkhttpProxyInfo.java @@ -8,19 +8,11 @@ import java.net.Proxy; * Proxy information. */ public class OkhttpProxyInfo { - /** - * Proxy types. - */ - public enum ProxyType { - NONE, HTTP, SOCKS4, SOCKS5 - } - private final String proxyAddress; private final int proxyPort; private final String proxyUsername; private final String proxyPassword; private final ProxyType proxyType; - public OkhttpProxyInfo(ProxyType proxyType, String proxyHost, int proxyPort, String proxyUser, String proxyPassword) { this.proxyType = proxyType; this.proxyAddress = proxyHost; @@ -29,8 +21,6 @@ public class OkhttpProxyInfo { this.proxyPassword = proxyPassword; } - // ---------------------------------------------------------------- factory - /** * Creates directProxy. */ @@ -38,6 +28,8 @@ public class OkhttpProxyInfo { return new OkhttpProxyInfo(ProxyType.NONE, null, 0, null, null); } + // ---------------------------------------------------------------- factory + /** * Creates SOCKS4 proxy. */ @@ -59,8 +51,6 @@ public class OkhttpProxyInfo { return new OkhttpProxyInfo(ProxyType.HTTP, proxyAddress, proxyPort, proxyUser, proxyPassword); } - // ---------------------------------------------------------------- getter - /** * Returns proxy type. */ @@ -68,6 +58,8 @@ public class OkhttpProxyInfo { return proxyType; } + // ---------------------------------------------------------------- getter + /** * Returns proxy address. */ @@ -99,6 +91,7 @@ public class OkhttpProxyInfo { /** * 返回 java.net.Proxy + * * @return */ public Proxy getProxy() { @@ -114,4 +107,11 @@ public class OkhttpProxyInfo { } return proxy; } + + /** + * Proxy types. + */ + public enum ProxyType { + NONE, HTTP, SOCKS4, SOCKS5 + } } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxGsonBuilder.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxGsonBuilder.java index 100ef523..9847d162 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxGsonBuilder.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxGsonBuilder.java @@ -2,7 +2,6 @@ package me.chanjar.weixin.common.util.json; import com.google.gson.Gson; import com.google.gson.GsonBuilder; - import me.chanjar.weixin.common.bean.WxAccessToken; import me.chanjar.weixin.common.bean.menu.WxMenu; import me.chanjar.weixin.common.bean.result.WxError; diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/res/StringManager.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/res/StringManager.java index 32f4e42a..3d66125e 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/res/StringManager.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/res/StringManager.java @@ -47,7 +47,7 @@ import java.util.*; public class StringManager { private static final Map> managers = - new Hashtable<>(); + new Hashtable<>(); private static int LOCALE_CACHE_SIZE = 10; /** * The ResourceBundle for this StringManager. @@ -103,7 +103,7 @@ public class StringManager { * @param packageName The package name */ public static final synchronized StringManager getManager( - String packageName) { + String packageName) { return getManager(packageName, Locale.getDefault()); } @@ -116,7 +116,7 @@ public class StringManager { * @param locale The Locale */ public static final synchronized StringManager getManager( - String packageName, Locale locale) { + String packageName, Locale locale) { Map map = managers.get(packageName); if (map == null) { @@ -133,7 +133,7 @@ public class StringManager { @Override protected boolean removeEldestEntry( - Map.Entry eldest) { + Map.Entry eldest) { return size() > (LOCALE_CACHE_SIZE - 1); } }; diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/xml/XStreamInitializer.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/xml/XStreamInitializer.java index ba49528a..aa2ce176 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/xml/XStreamInitializer.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/xml/XStreamInitializer.java @@ -1,7 +1,5 @@ package me.chanjar.weixin.common.util.xml; -import java.io.Writer; - import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.core.util.QuickWriter; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; @@ -10,6 +8,8 @@ import com.thoughtworks.xstream.io.xml.XppDriver; import com.thoughtworks.xstream.security.NullPermission; import com.thoughtworks.xstream.security.PrimitiveTypePermission; +import java.io.Writer; + public class XStreamInitializer { public static XStream getInstance() { diff --git a/weixin-java-common/src/test/java/me/chanjar/weixin/common/bean/WxAccessTokenTest.java b/weixin-java-common/src/test/java/me/chanjar/weixin/common/bean/WxAccessTokenTest.java index b2bc7fe7..1f88df29 100644 --- a/weixin-java-common/src/test/java/me/chanjar/weixin/common/bean/WxAccessTokenTest.java +++ b/weixin-java-common/src/test/java/me/chanjar/weixin/common/bean/WxAccessTokenTest.java @@ -1,7 +1,7 @@ package me.chanjar.weixin.common.bean; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.testng.*; +import org.testng.annotations.*; @Test public class WxAccessTokenTest { diff --git a/weixin-java-common/src/test/java/me/chanjar/weixin/common/bean/WxErrorTest.java b/weixin-java-common/src/test/java/me/chanjar/weixin/common/bean/WxErrorTest.java index 3fe40795..477fcdab 100644 --- a/weixin-java-common/src/test/java/me/chanjar/weixin/common/bean/WxErrorTest.java +++ b/weixin-java-common/src/test/java/me/chanjar/weixin/common/bean/WxErrorTest.java @@ -1,8 +1,8 @@ package me.chanjar.weixin.common.bean; import me.chanjar.weixin.common.bean.result.WxError; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.testng.*; +import org.testng.annotations.*; @Test public class WxErrorTest { diff --git a/weixin-java-common/src/test/java/me/chanjar/weixin/common/bean/WxMenuTest.java b/weixin-java-common/src/test/java/me/chanjar/weixin/common/bean/WxMenuTest.java index e2a0c2c1..506b2dba 100644 --- a/weixin-java-common/src/test/java/me/chanjar/weixin/common/bean/WxMenuTest.java +++ b/weixin-java-common/src/test/java/me/chanjar/weixin/common/bean/WxMenuTest.java @@ -1,12 +1,10 @@ package me.chanjar.weixin.common.bean; -import org.testng.Assert; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; - import me.chanjar.weixin.common.bean.menu.WxMenu; import me.chanjar.weixin.common.bean.menu.WxMenuButton; import me.chanjar.weixin.common.bean.menu.WxMenuRule; +import org.testng.*; +import org.testng.annotations.*; @Test public class WxMenuTest { @@ -87,75 +85,75 @@ public class WxMenuTest { Object[][] res = menuJson(); String json = "{ \"menu\" : " + res[0][0] + " }"; return new Object[][]{ - new Object[]{json} + new Object[]{json} }; } @DataProvider(name = "wxPushMenu") public Object[][] menuJson() { String json = - "{" - + "\"button\":[" - + "{" - + "\"type\":\"click\"," - + "\"name\":\"今日歌曲\"," - + "\"key\":\"V1001_TODAY_MUSIC\"" - + "}," - + "{" - + "\"type\":\"click\"," - + "\"name\":\"歌手简介\"," - + "\"key\":\"V1001_TODAY_SINGER\"" - + "}," - + "{" - + "\"name\":\"菜单\"," - + "\"sub_button\":[" - + "{" - + "\"type\":\"view\"," - + "\"name\":\"搜索\"," - + "\"url\":\"http://www.soso.com/\"" - + "}," - + "{" - + "\"type\":\"view\"," - + "\"name\":\"视频\"," - + "\"url\":\"http://v.qq.com/\"" - + "}," - + "{" - + "\"type\":\"click\"," - + "\"name\":\"赞一下我们\"," - + "\"key\":\"V1001_GOOD\"" - + "}" - + "]" - + "}" - + "]" - + "}"; + "{" + + "\"button\":[" + + "{" + + "\"type\":\"click\"," + + "\"name\":\"今日歌曲\"," + + "\"key\":\"V1001_TODAY_MUSIC\"" + + "}," + + "{" + + "\"type\":\"click\"," + + "\"name\":\"歌手简介\"," + + "\"key\":\"V1001_TODAY_SINGER\"" + + "}," + + "{" + + "\"name\":\"菜单\"," + + "\"sub_button\":[" + + "{" + + "\"type\":\"view\"," + + "\"name\":\"搜索\"," + + "\"url\":\"http://www.soso.com/\"" + + "}," + + "{" + + "\"type\":\"view\"," + + "\"name\":\"视频\"," + + "\"url\":\"http://v.qq.com/\"" + + "}," + + "{" + + "\"type\":\"click\"," + + "\"name\":\"赞一下我们\"," + + "\"key\":\"V1001_GOOD\"" + + "}" + + "]" + + "}" + + "]" + + "}"; return new Object[][]{ - new Object[]{json} + new Object[]{json} }; } @DataProvider(name = "wxAddConditionalMenu") public Object[][] addConditionalMenuJson() { String json = - "{" - + "\"button\":[" - + "{" - + "\"type\":\"click\"," - + "\"name\":\"今日歌曲\"," - + "\"key\":\"V1001_TODAY_MUSIC\"" - + "}" - + "]," - + "\"matchrule\":{" - + "\"group_id\":\"2\"," - + "\"sex\":\"1\"," - + "\"country\":\"中国\"," - + "\"province\":\"广东\"," - + "\"city\":\"广州\"," - + "\"client_platform_type\":\"2\"," - + "\"language\":\"zh_CN\"" - + "}" - + "}"; + "{" + + "\"button\":[" + + "{" + + "\"type\":\"click\"," + + "\"name\":\"今日歌曲\"," + + "\"key\":\"V1001_TODAY_MUSIC\"" + + "}" + + "]," + + "\"matchrule\":{" + + "\"group_id\":\"2\"," + + "\"sex\":\"1\"," + + "\"country\":\"中国\"," + + "\"province\":\"广东\"," + + "\"city\":\"广州\"," + + "\"client_platform_type\":\"2\"," + + "\"language\":\"zh_CN\"" + + "}" + + "}"; return new Object[][]{ - new Object[]{json} + new Object[]{json} }; } diff --git a/weixin-java-common/src/test/java/me/chanjar/weixin/common/session/SessionTest.java b/weixin-java-common/src/test/java/me/chanjar/weixin/common/session/SessionTest.java index e0248c79..93ad2bfc 100644 --- a/weixin-java-common/src/test/java/me/chanjar/weixin/common/session/SessionTest.java +++ b/weixin-java-common/src/test/java/me/chanjar/weixin/common/session/SessionTest.java @@ -1,8 +1,7 @@ package me.chanjar.weixin.common.session; -import org.testng.Assert; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.testng.*; +import org.testng.annotations.*; @Test public class SessionTest { @@ -11,7 +10,7 @@ public class SessionTest { public Object[][] getSessionManager() { return new Object[][]{ - new Object[]{new StandardSessionManager()} + new Object[]{new StandardSessionManager()} }; } diff --git a/weixin-java-common/src/test/java/me/chanjar/weixin/common/util/WxMessageInMemoryDuplicateCheckerTest.java b/weixin-java-common/src/test/java/me/chanjar/weixin/common/util/WxMessageInMemoryDuplicateCheckerTest.java index a3a243a4..c1495842 100644 --- a/weixin-java-common/src/test/java/me/chanjar/weixin/common/util/WxMessageInMemoryDuplicateCheckerTest.java +++ b/weixin-java-common/src/test/java/me/chanjar/weixin/common/util/WxMessageInMemoryDuplicateCheckerTest.java @@ -1,8 +1,8 @@ package me.chanjar.weixin.common.util; import me.chanjar.weixin.common.api.WxMessageInMemoryDuplicateChecker; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.testng.*; +import org.testng.annotations.*; @Test public class WxMessageInMemoryDuplicateCheckerTest { diff --git a/weixin-java-common/src/test/java/me/chanjar/weixin/common/util/crypto/WxCryptUtilTest.java b/weixin-java-common/src/test/java/me/chanjar/weixin/common/util/crypto/WxCryptUtilTest.java index 91095a20..b13fee5f 100755 --- a/weixin-java-common/src/test/java/me/chanjar/weixin/common/util/crypto/WxCryptUtilTest.java +++ b/weixin-java-common/src/test/java/me/chanjar/weixin/common/util/crypto/WxCryptUtilTest.java @@ -1,6 +1,6 @@ package me.chanjar.weixin.common.util.crypto; -import org.testng.annotations.Test; +import org.testng.annotations.*; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; @@ -13,8 +13,7 @@ import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.io.StringReader; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; +import static org.testng.Assert.*; @Test public class WxCryptUtilTest { @@ -77,7 +76,7 @@ public class WxCryptUtilTest { } public void testValidateSignatureError() throws ParserConfigurationException, SAXException, - IOException { + IOException { try { WxCryptUtil pc = new WxCryptUtil(this.token, this.encodingAesKey, this.appId); String afterEncrpt = pc.encrypt(this.replyMsg); diff --git a/weixin-java-common/src/test/resources/logback-test.xml b/weixin-java-common/src/test/resources/logback-test.xml index 2c421e49..e6903423 100644 --- a/weixin-java-common/src/test/resources/logback-test.xml +++ b/weixin-java-common/src/test/resources/logback-test.xml @@ -10,8 +10,8 @@ - + - + diff --git a/weixin-java-common/src/test/resources/testng.xml b/weixin-java-common/src/test/resources/testng.xml index f2222275..793ba0a6 100644 --- a/weixin-java-common/src/test/resources/testng.xml +++ b/weixin-java-common/src/test/resources/testng.xml @@ -8,7 +8,7 @@ - + diff --git a/weixin-java-cp/build.gradle b/weixin-java-cp/build.gradle index 85d7c4bb..3e0c09ad 100644 --- a/weixin-java-cp/build.gradle +++ b/weixin-java-cp/build.gradle @@ -1,12 +1,11 @@ - description = 'WeiXin Java Tools - CP' dependencies { compile project(':weixin-java-common') - testCompile group: 'junit', name: 'junit', version:'4.11' - testCompile group: 'org.testng', name: 'testng', version:'6.8.7' - testCompile group: 'org.mockito', name: 'mockito-all', version:'1.9.5' - testCompile group: 'com.google.inject', name: 'guice', version:'3.0' - testCompile group: 'org.eclipse.jetty', name: 'jetty-server', version:'9.3.0.RC0' - testCompile group: 'org.eclipse.jetty', name: 'jetty-servlet', version:'9.3.0.RC0' + testCompile group: 'junit', name: 'junit', version: '4.11' + testCompile group: 'org.testng', name: 'testng', version: '6.8.7' + testCompile group: 'org.mockito', name: 'mockito-all', version: '1.9.5' + testCompile group: 'com.google.inject', name: 'guice', version: '3.0' + testCompile group: 'org.eclipse.jetty', name: 'jetty-server', version: '9.3.0.RC0' + testCompile group: 'org.eclipse.jetty', name: 'jetty-servlet', version: '9.3.0.RC0' } test.useTestNG() diff --git a/weixin-java-cp/pom.xml b/weixin-java-cp/pom.xml index e2afcb41..68ad8283 100644 --- a/weixin-java-cp/pom.xml +++ b/weixin-java-cp/pom.xml @@ -1,7 +1,8 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" + xmlns="http://maven.apache.org/POM/4.0.0"> 4.0.0 com.github.binarywang diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpJedisConfigStorage.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpJedisConfigStorage.java index 019cfc38..25f5e288 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpJedisConfigStorage.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpJedisConfigStorage.java @@ -39,13 +39,13 @@ public class WxCpJedisConfigStorage implements WxCpConfigStorage { this.jedisPool = new JedisPool(host, port); } - + public WxCpJedisConfigStorage(JedisPoolConfig poolConfig, String host, int port) { - this.jedisPool = new JedisPool(poolConfig, host, port); + this.jedisPool = new JedisPool(poolConfig, host, port); } - + public WxCpJedisConfigStorage(JedisPoolConfig poolConfig, String host, int port, int timeout, final String password) { - this.jedisPool = new JedisPool(poolConfig, host, port, timeout, password); + this.jedisPool = new JedisPool(poolConfig, host, port, timeout, password); } /** diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpService.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpService.java index f02b7589..6e30ce55 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpService.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpService.java @@ -481,13 +481,6 @@ public interface WxCpService { */ T execute(RequestExecutor executor, String uri, E data) throws WxErrorException; - /** - * 注入 {@link WxCpConfigStorage} 的实现 - * - * @param wxConfigProvider 配置对象 - */ - void setWxCpConfigStorage(WxCpConfigStorage wxConfigProvider); - /** *
        * 设置当微信系统响应系统繁忙时,要等待多少 retrySleepMillis(ms) * 2^(重试次数 - 1) 再发起重试
    @@ -563,4 +556,11 @@ public interface WxCpService {
        * @return WxMpConfigStorage
        */
       WxCpConfigStorage getWxCpConfigStorage();
    +
    +  /**
    +   * 注入 {@link WxCpConfigStorage} 的实现
    +   *
    +   * @param wxConfigProvider 配置对象
    +   */
    +  void setWxCpConfigStorage(WxCpConfigStorage wxConfigProvider);
     }
    diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/impl/okhttp/WxCpServiceImpl.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/impl/okhttp/WxCpServiceImpl.java
    index ae4eab2c..48f4b670 100644
    --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/impl/okhttp/WxCpServiceImpl.java
    +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/impl/okhttp/WxCpServiceImpl.java
    @@ -1,7 +1,5 @@
     package me.chanjar.weixin.cp.api.impl.okhttp;
     
    -import java.io.IOException;
    -
     import me.chanjar.weixin.common.bean.WxAccessToken;
     import me.chanjar.weixin.common.bean.result.WxError;
     import me.chanjar.weixin.common.exception.WxErrorException;
    @@ -11,6 +9,8 @@ import me.chanjar.weixin.cp.api.WxCpConfigStorage;
     import me.chanjar.weixin.cp.api.impl.AbstractWxCpServiceImpl;
     import okhttp3.*;
     
    +import java.io.IOException;
    +
     public class WxCpServiceImpl extends AbstractWxCpServiceImpl {
       protected ConnectionPool httpClient;
       protected OkhttpProxyInfo httpProxy;
    diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpDepart.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpDepart.java
    index a679dffe..118c5004 100644
    --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpDepart.java
    +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpDepart.java
    @@ -1,9 +1,9 @@
     package me.chanjar.weixin.cp.bean;
     
    -import java.io.Serializable;
    -
     import me.chanjar.weixin.cp.util.json.WxCpGsonBuilder;
     
    +import java.io.Serializable;
    +
     /**
      * 微信部门
      *
    @@ -60,10 +60,10 @@ public class WxCpDepart implements Serializable {
       @Override
       public String toString() {
         return "WxCpDepart{" +
    -            "id=" + this.id +
    -            ", name='" + this.name + '\'' +
    -            ", parentId=" + this.parentId +
    -            ", order=" + this.order +
    -            '}';
    +      "id=" + this.id +
    +      ", name='" + this.name + '\'' +
    +      ", parentId=" + this.parentId +
    +      ", order=" + this.order +
    +      '}';
       }
     }
    diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpMessage.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpMessage.java
    index 324df209..2d07fcf8 100644
    --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpMessage.java
    +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpMessage.java
    @@ -33,14 +33,6 @@ public class WxCpMessage implements Serializable {
       private List articles = new ArrayList<>();
       private List mpnewsArticles = new ArrayList<>();
     
    -  public List getMpnewsArticles() {
    -    return mpnewsArticles;
    -  }
    -
    -  public void setMpnewsArticles(List mpnewsArticles) {
    -    this.mpnewsArticles = mpnewsArticles;
    -  }
    -
       /**
        * 获得文本消息builder
        */
    @@ -90,6 +82,14 @@ public class WxCpMessage implements Serializable {
         return new FileBuilder();
       }
     
    +  public List getMpnewsArticles() {
    +    return mpnewsArticles;
    +  }
    +
    +  public void setMpnewsArticles(List mpnewsArticles) {
    +    this.mpnewsArticles = mpnewsArticles;
    +  }
    +
       public String getToUser() {
         return this.toUser;
       }
    diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpTag.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpTag.java
    index 4e1c034f..79ec3f13 100644
    --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpTag.java
    +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpTag.java
    @@ -1,9 +1,9 @@
     package me.chanjar.weixin.cp.bean;
     
    -import java.io.Serializable;
    -
     import me.chanjar.weixin.cp.util.json.WxCpGsonBuilder;
     
    +import java.io.Serializable;
    +
     /**
      * Created by Daniel Qian
      */
    diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpUser.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpUser.java
    index 93c3e5fe..a3adca98 100644
    --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpUser.java
    +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpUser.java
    @@ -1,11 +1,11 @@
     package me.chanjar.weixin.cp.bean;
     
    +import me.chanjar.weixin.cp.util.json.WxCpGsonBuilder;
    +
     import java.io.Serializable;
     import java.util.ArrayList;
     import java.util.List;
     
    -import me.chanjar.weixin.cp.util.json.WxCpGsonBuilder;
    -
     /**
      * 微信用户信息
      *
    diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlMessage.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlMessage.java
    index 93ca45c3..3c0f50b8 100644
    --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlMessage.java
    +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlMessage.java
    @@ -1,20 +1,18 @@
     package me.chanjar.weixin.cp.bean;
     
    -import java.io.IOException;
    -import java.io.InputStream;
    -import java.io.Serializable;
    -import java.util.ArrayList;
    -import java.util.List;
    -
    -import org.apache.commons.io.IOUtils;
    -
     import com.thoughtworks.xstream.annotations.XStreamAlias;
     import com.thoughtworks.xstream.annotations.XStreamConverter;
    -
     import me.chanjar.weixin.common.util.xml.XStreamCDataConverter;
     import me.chanjar.weixin.cp.api.WxCpConfigStorage;
     import me.chanjar.weixin.cp.util.crypto.WxCpCryptUtil;
     import me.chanjar.weixin.cp.util.xml.XStreamTransformer;
    +import org.apache.commons.io.IOUtils;
    +
    +import java.io.IOException;
    +import java.io.InputStream;
    +import java.io.Serializable;
    +import java.util.ArrayList;
    +import java.util.List;
     
     /**
      * 
    @@ -183,18 +181,18 @@ public class WxCpXmlMessage implements Serializable {
        * @param msgSignature
        */
       public static WxCpXmlMessage fromEncryptedXml(
    -          String encryptedXml,
    -          WxCpConfigStorage wxCpConfigStorage,
    -          String timestamp, String nonce, String msgSignature) {
    +    String encryptedXml,
    +    WxCpConfigStorage wxCpConfigStorage,
    +    String timestamp, String nonce, String msgSignature) {
         WxCpCryptUtil cryptUtil = new WxCpCryptUtil(wxCpConfigStorage);
         String plainText = cryptUtil.decrypt(msgSignature, timestamp, nonce, encryptedXml);
         return fromXml(plainText);
       }
     
       public static WxCpXmlMessage fromEncryptedXml(
    -          InputStream is,
    -          WxCpConfigStorage wxCpConfigStorage,
    -          String timestamp, String nonce, String msgSignature) {
    +    InputStream is,
    +    WxCpConfigStorage wxCpConfigStorage,
    +    String timestamp, String nonce, String msgSignature) {
         try {
           return fromEncryptedXml(IOUtils.toString(is, "UTF-8"), wxCpConfigStorage, timestamp, nonce, msgSignature);
         } catch (IOException e) {
    @@ -493,40 +491,40 @@ public class WxCpXmlMessage implements Serializable {
       @Override
       public String toString() {
         return "WxCpXmlMessage{" +
    -            "agentId=" + this.agentId +
    -            ", toUserName='" + this.toUserName + '\'' +
    -            ", fromUserName='" + this.fromUserName + '\'' +
    -            ", createTime=" + this.createTime +
    -            ", msgType='" + this.msgType + '\'' +
    -            ", content='" + this.content + '\'' +
    -            ", msgId=" + this.msgId +
    -            ", picUrl='" + this.picUrl + '\'' +
    -            ", mediaId='" + this.mediaId + '\'' +
    -            ", format='" + this.format + '\'' +
    -            ", thumbMediaId='" + this.thumbMediaId + '\'' +
    -            ", locationX=" + this.locationX +
    -            ", locationY=" + this.locationY +
    -            ", scale=" + this.scale +
    -            ", label='" + this.label + '\'' +
    -            ", title='" + this.title + '\'' +
    -            ", description='" + this.description + '\'' +
    -            ", url='" + this.url + '\'' +
    -            ", event='" + this.event + '\'' +
    -            ", eventKey='" + this.eventKey + '\'' +
    -            ", ticket='" + this.ticket + '\'' +
    -            ", latitude=" + this.latitude +
    -            ", longitude=" + this.longitude +
    -            ", precision=" + this.precision +
    -            ", recognition='" + this.recognition + '\'' +
    -            ", status='" + this.status + '\'' +
    -            ", totalCount=" + this.totalCount +
    -            ", filterCount=" + this.filterCount +
    -            ", sentCount=" + this.sentCount +
    -            ", errorCount=" + this.errorCount +
    -            ", scanCodeInfo=" + this.scanCodeInfo +
    -            ", sendPicsInfo=" + this.sendPicsInfo +
    -            ", sendLocationInfo=" + this.sendLocationInfo +
    -            '}';
    +      "agentId=" + this.agentId +
    +      ", toUserName='" + this.toUserName + '\'' +
    +      ", fromUserName='" + this.fromUserName + '\'' +
    +      ", createTime=" + this.createTime +
    +      ", msgType='" + this.msgType + '\'' +
    +      ", content='" + this.content + '\'' +
    +      ", msgId=" + this.msgId +
    +      ", picUrl='" + this.picUrl + '\'' +
    +      ", mediaId='" + this.mediaId + '\'' +
    +      ", format='" + this.format + '\'' +
    +      ", thumbMediaId='" + this.thumbMediaId + '\'' +
    +      ", locationX=" + this.locationX +
    +      ", locationY=" + this.locationY +
    +      ", scale=" + this.scale +
    +      ", label='" + this.label + '\'' +
    +      ", title='" + this.title + '\'' +
    +      ", description='" + this.description + '\'' +
    +      ", url='" + this.url + '\'' +
    +      ", event='" + this.event + '\'' +
    +      ", eventKey='" + this.eventKey + '\'' +
    +      ", ticket='" + this.ticket + '\'' +
    +      ", latitude=" + this.latitude +
    +      ", longitude=" + this.longitude +
    +      ", precision=" + this.precision +
    +      ", recognition='" + this.recognition + '\'' +
    +      ", status='" + this.status + '\'' +
    +      ", totalCount=" + this.totalCount +
    +      ", filterCount=" + this.filterCount +
    +      ", sentCount=" + this.sentCount +
    +      ", errorCount=" + this.errorCount +
    +      ", scanCodeInfo=" + this.scanCodeInfo +
    +      ", sendPicsInfo=" + this.sendPicsInfo +
    +      ", sendLocationInfo=" + this.sendLocationInfo +
    +      '}';
       }
     
       @XStreamAlias("ScanCodeInfo")
    diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutImageMessage.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutImageMessage.java
    index 35cbe754..2ddb78af 100644
    --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutImageMessage.java
    +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutImageMessage.java
    @@ -2,7 +2,6 @@ package me.chanjar.weixin.cp.bean;
     
     import com.thoughtworks.xstream.annotations.XStreamAlias;
     import com.thoughtworks.xstream.annotations.XStreamConverter;
    -
     import me.chanjar.weixin.common.api.WxConsts;
     import me.chanjar.weixin.common.util.xml.XStreamMediaIdConverter;
     
    diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutNewsMessage.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutNewsMessage.java
    index 8910f03f..09978410 100644
    --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutNewsMessage.java
    +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutNewsMessage.java
    @@ -1,14 +1,13 @@
     package me.chanjar.weixin.cp.bean;
     
    -import java.util.ArrayList;
    -import java.util.List;
    -
     import com.thoughtworks.xstream.annotations.XStreamAlias;
     import com.thoughtworks.xstream.annotations.XStreamConverter;
    -
     import me.chanjar.weixin.common.api.WxConsts;
     import me.chanjar.weixin.common.util.xml.XStreamCDataConverter;
     
    +import java.util.ArrayList;
    +import java.util.List;
    +
     @XStreamAlias("xml")
     public class WxCpXmlOutNewsMessage extends WxCpXmlOutMessage {
       private static final long serialVersionUID = -5796178637883178826L;
    diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutTextMessage.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutTextMessage.java
    index 532e06c3..5f09abf4 100644
    --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutTextMessage.java
    +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutTextMessage.java
    @@ -2,7 +2,6 @@ package me.chanjar.weixin.cp.bean;
     
     import com.thoughtworks.xstream.annotations.XStreamAlias;
     import com.thoughtworks.xstream.annotations.XStreamConverter;
    -
     import me.chanjar.weixin.common.api.WxConsts;
     import me.chanjar.weixin.common.util.xml.XStreamCDataConverter;
     
    diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVideoMessage.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVideoMessage.java
    index 73c56d4c..46dae31c 100644
    --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVideoMessage.java
    +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVideoMessage.java
    @@ -2,7 +2,6 @@ package me.chanjar.weixin.cp.bean;
     
     import com.thoughtworks.xstream.annotations.XStreamAlias;
     import com.thoughtworks.xstream.annotations.XStreamConverter;
    -
     import me.chanjar.weixin.common.api.WxConsts;
     import me.chanjar.weixin.common.util.xml.XStreamCDataConverter;
     
    diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVoiceMessage.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVoiceMessage.java
    index bba95cfd..b1827706 100644
    --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVoiceMessage.java
    +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVoiceMessage.java
    @@ -2,7 +2,6 @@ package me.chanjar.weixin.cp.bean;
     
     import com.thoughtworks.xstream.annotations.XStreamAlias;
     import com.thoughtworks.xstream.annotations.XStreamConverter;
    -
     import me.chanjar.weixin.common.api.WxConsts;
     import me.chanjar.weixin.common.util.xml.XStreamMediaIdConverter;
     
    diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/article/MpnewsArticle.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/article/MpnewsArticle.java
    index 7904da20..82c4e2aa 100644
    --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/article/MpnewsArticle.java
    +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/article/MpnewsArticle.java
    @@ -4,6 +4,7 @@ package me.chanjar.weixin.cp.bean.article;
      * 
      *  Created by BinaryWang on 2017/3/27.
      * 
    + * * @author Binary Wang */ public class MpnewsArticle { diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/BaseBuilder.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/BaseBuilder.java index 7800f1c6..ea3e710c 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/BaseBuilder.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/BaseBuilder.java @@ -44,7 +44,7 @@ public class BaseBuilder { m.setToParty(this.toParty); m.setToTag(this.toTag); m.setSafe( - (this.safe == null || "".equals(this.safe)) ? WxConsts.CUSTOM_MSG_SAFE_NO : this.safe); + (this.safe == null || "".equals(this.safe)) ? WxConsts.CUSTOM_MSG_SAFE_NO : this.safe); return m; } diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/crypto/WxCpCryptUtil.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/crypto/WxCpCryptUtil.java index 104b1243..2b2dfe47 100755 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/crypto/WxCpCryptUtil.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/crypto/WxCpCryptUtil.java @@ -1,47 +1,51 @@ -/** - * 对公众平台发送给公众账号的消息加解密示例代码. - * - * @copyright Copyright (c) 1998-2014 Tencent Inc. - *

    - * 针对org.apache.commons.codec.binary.Base64, - * 需要导入架包commons-codec-1.9(或commons-codec-1.8等其他版本) - * 官方下载地址:http://commons.apache.org/proper/commons-codec/download_codec.cgi - */ - -// ------------------------------------------------------------------------ - -/** - * 针对org.apache.commons.codec.binary.Base64, - * 需要导入架包commons-codec-1.9(或commons-codec-1.8等其他版本) - * 官方下载地址:http://commons.apache.org/proper/commons-codec/download_codec.cgi - */ -package me.chanjar.weixin.cp.util.crypto; - -import me.chanjar.weixin.common.util.crypto.WxCryptUtil; -import me.chanjar.weixin.cp.api.WxCpConfigStorage; -import org.apache.commons.codec.binary.Base64; - -public class WxCpCryptUtil extends WxCryptUtil { - - /** - * 构造函数 - * - * @param wxCpConfigStorage - */ - public WxCpCryptUtil(WxCpConfigStorage wxCpConfigStorage) { - /* - * @param token 公众平台上,开发者设置的token - * @param encodingAesKey 公众平台上,开发者设置的EncodingAESKey - * @param appidOrCorpid 公众平台appid - */ - String encodingAesKey = wxCpConfigStorage.getAesKey(); - String token = wxCpConfigStorage.getToken(); - String corpId = wxCpConfigStorage.getCorpId(); - - this.token = token; - this.appidOrCorpid = corpId; - this.aesKey = Base64.decodeBase64(encodingAesKey + "="); - } - - -} +/** + * 对公众平台发送给公众账号的消息加解密示例代码. + * + * @copyright Copyright (c) 1998-2014 Tencent Inc. + *

    + * 针对org.apache.commons.codec.binary.Base64, + * 需要导入架包commons-codec-1.9(或commons-codec-1.8等其他版本) + * 官方下载地址:http://commons.apache.org/proper/commons-codec/download_codec.cgi + *

    + * 针对org.apache.commons.codec.binary.Base64, + * 需要导入架包commons-codec-1.9(或commons-codec-1.8等其他版本) + * 官方下载地址:http://commons.apache.org/proper/commons-codec/download_codec.cgi + */ + +// ------------------------------------------------------------------------ + +/** + * 针对org.apache.commons.codec.binary.Base64, + * 需要导入架包commons-codec-1.9(或commons-codec-1.8等其他版本) + * 官方下载地址:http://commons.apache.org/proper/commons-codec/download_codec.cgi + */ +package me.chanjar.weixin.cp.util.crypto; + +import me.chanjar.weixin.common.util.crypto.WxCryptUtil; +import me.chanjar.weixin.cp.api.WxCpConfigStorage; +import org.apache.commons.codec.binary.Base64; + +public class WxCpCryptUtil extends WxCryptUtil { + + /** + * 构造函数 + * + * @param wxCpConfigStorage + */ + public WxCpCryptUtil(WxCpConfigStorage wxCpConfigStorage) { + /* + * @param token 公众平台上,开发者设置的token + * @param encodingAesKey 公众平台上,开发者设置的EncodingAESKey + * @param appidOrCorpid 公众平台appid + */ + String encodingAesKey = wxCpConfigStorage.getAesKey(); + String token = wxCpConfigStorage.getToken(); + String corpId = wxCpConfigStorage.getCorpId(); + + this.token = token; + this.appidOrCorpid = corpId; + this.aesKey = Base64.decodeBase64(encodingAesKey + "="); + } + + +} diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpDepartGsonAdapter.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpDepartGsonAdapter.java index a547ce02..431c3803 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpDepartGsonAdapter.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpDepartGsonAdapter.java @@ -39,7 +39,7 @@ public class WxCpDepartGsonAdapter implements JsonSerializer, JsonDe @Override public WxCpDepart deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) - throws JsonParseException { + throws JsonParseException { WxCpDepart depart = new WxCpDepart(); JsonObject departJson = json.getAsJsonObject(); if (departJson.get("id") != null && !departJson.get("id").isJsonNull()) { diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpMessageGsonAdapter.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpMessageGsonAdapter.java index 1cf2d312..a74c17b6 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpMessageGsonAdapter.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpMessageGsonAdapter.java @@ -93,7 +93,7 @@ public class WxCpMessageGsonAdapter implements JsonSerializer { JsonObject newsJsonObject = new JsonObject(); if (message.getMediaId() != null) { newsJsonObject.addProperty("media_id", message.getMediaId()); - }else { + } else { JsonArray articleJsonArray = new JsonArray(); for (MpnewsArticle article : message.getMpnewsArticles()) { JsonObject articleJson = new JsonObject(); diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpTagGsonAdapter.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpTagGsonAdapter.java index 43e84a00..87219068 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpTagGsonAdapter.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpTagGsonAdapter.java @@ -29,7 +29,7 @@ public class WxCpTagGsonAdapter implements JsonSerializer, JsonDeserial @Override public WxCpTag deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) - throws JsonParseException { + throws JsonParseException { JsonObject jsonObject = json.getAsJsonObject(); return new WxCpTag(GsonHelper.getString(jsonObject, "tagid"), GsonHelper.getString(jsonObject, "tagname")); } diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpUserGsonAdapter.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpUserGsonAdapter.java index bbabf054..4a8a9010 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpUserGsonAdapter.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpUserGsonAdapter.java @@ -21,7 +21,7 @@ public class WxCpUserGsonAdapter implements JsonDeserializer, JsonSeri @Override public WxCpUser deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) - throws JsonParseException { + throws JsonParseException { JsonObject o = json.getAsJsonObject(); WxCpUser user = new WxCpUser(); user.setUserId(GsonHelper.getString(o, "userid")); @@ -50,8 +50,8 @@ public class WxCpUserGsonAdapter implements JsonDeserializer, JsonSeri JsonArray attrJsonElements = o.get("extattr").getAsJsonObject().get("attrs").getAsJsonArray(); for (JsonElement attrJsonElement : attrJsonElements) { WxCpUser.Attr attr = new WxCpUser.Attr( - GsonHelper.getString(attrJsonElement.getAsJsonObject(), "name"), - GsonHelper.getString(attrJsonElement.getAsJsonObject(), "value") + GsonHelper.getString(attrJsonElement.getAsJsonObject(), "name"), + GsonHelper.getString(attrJsonElement.getAsJsonObject(), "value") ); user.getExtAttrs().add(attr); } diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/ApiTestModule.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/ApiTestModule.java index 80265168..d498cc5a 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/ApiTestModule.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/ApiTestModule.java @@ -1,16 +1,15 @@ package me.chanjar.weixin.cp.api; -import java.io.IOException; -import java.io.InputStream; - import com.google.inject.Binder; import com.google.inject.Module; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.annotations.XStreamAlias; - import me.chanjar.weixin.common.util.xml.XStreamInitializer; import me.chanjar.weixin.cp.api.impl.apache.WxCpServiceImpl; +import java.io.IOException; +import java.io.InputStream; + public class ApiTestModule implements Module { public static T fromXml(Class clazz, InputStream is) { @@ -23,9 +22,9 @@ public class ApiTestModule implements Module { @Override public void configure(Binder binder) { try (InputStream is1 = ClassLoader - .getSystemResourceAsStream("test-config.xml")) { + .getSystemResourceAsStream("test-config.xml")) { WxXmlCpInMemoryConfigStorage config = fromXml( - WxXmlCpInMemoryConfigStorage.class, is1); + WxXmlCpInMemoryConfigStorage.class, is1); WxCpServiceImpl wxService = new WxCpServiceImpl(); wxService.setWxCpConfigStorage(config); @@ -72,10 +71,10 @@ public class ApiTestModule implements Module { @Override public String toString() { return super.toString() + " > WxXmlCpConfigStorage{" + - "userId='" + this.userId + '\'' + - ", departmentId='" + this.departmentId + '\'' + - ", tagId='" + this.tagId + '\'' + - '}'; + "userId='" + this.userId + '\'' + + ", departmentId='" + this.departmentId + '\'' + + ", tagId='" + this.tagId + '\'' + + '}'; } } diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpDepartAPITest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpDepartAPITest.java index 1a3fb795..58c142ff 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpDepartAPITest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpDepartAPITest.java @@ -1,16 +1,13 @@ package me.chanjar.weixin.cp.api; -import java.util.List; - -import me.chanjar.weixin.cp.api.impl.apache.WxCpServiceImpl; -import org.testng.Assert; -import org.testng.annotations.Guice; -import org.testng.annotations.Test; - import com.google.inject.Inject; - import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.cp.api.impl.apache.WxCpServiceImpl; import me.chanjar.weixin.cp.bean.WxCpDepart; +import org.testng.*; +import org.testng.annotations.*; + +import java.util.List; /** * 测试部门接口 diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpMediaAPITest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpMediaAPITest.java index 3f297968..b289bdbb 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpMediaAPITest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpMediaAPITest.java @@ -1,21 +1,17 @@ package me.chanjar.weixin.cp.api; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -import me.chanjar.weixin.cp.api.impl.apache.WxCpServiceImpl; -import org.testng.Assert; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Guice; -import org.testng.annotations.Test; - import com.google.inject.Inject; - import me.chanjar.weixin.common.api.WxConsts; import me.chanjar.weixin.common.bean.result.WxMediaUploadResult; import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.cp.api.impl.apache.WxCpServiceImpl; +import org.testng.*; +import org.testng.annotations.*; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; /** * 测试多媒体文件上传下载 @@ -35,13 +31,13 @@ public class WxCpMediaAPITest { @Test(dataProvider = "uploadMedia") public void testUploadMedia(String mediaType, String fileType, String fileName) throws WxErrorException, IOException { try (InputStream inputStream = ClassLoader - .getSystemResourceAsStream(fileName);) { + .getSystemResourceAsStream(fileName);) { WxMediaUploadResult res = this.wxService.mediaUpload(mediaType, fileType, - inputStream); + inputStream); Assert.assertNotNull(res.getType()); Assert.assertNotNull(res.getCreatedAt()); Assert.assertTrue( - res.getMediaId() != null || res.getThumbMediaId() != null); + res.getMediaId() != null || res.getThumbMediaId() != null); if (res.getMediaId() != null) { this.media_ids.add(res.getMediaId()); @@ -55,10 +51,10 @@ public class WxCpMediaAPITest { @DataProvider public Object[][] uploadMedia() { return new Object[][]{ - new Object[]{WxConsts.MEDIA_IMAGE, TestConstants.FILE_JPG, "mm.jpeg"}, - new Object[]{WxConsts.MEDIA_VOICE, TestConstants.FILE_MP3, "mm.mp3"}, - new Object[]{WxConsts.MEDIA_VIDEO, TestConstants.FILE_MP4, "mm.mp4"}, - new Object[]{WxConsts.MEDIA_FILE, TestConstants.FILE_JPG, "mm.jpeg"} + new Object[]{WxConsts.MEDIA_IMAGE, TestConstants.FILE_JPG, "mm.jpeg"}, + new Object[]{WxConsts.MEDIA_VOICE, TestConstants.FILE_MP3, "mm.mp3"}, + new Object[]{WxConsts.MEDIA_VIDEO, TestConstants.FILE_MP4, "mm.mp4"}, + new Object[]{WxConsts.MEDIA_FILE, TestConstants.FILE_JPG, "mm.jpeg"} }; } diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpMessageRouterTest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpMessageRouterTest.java index 4b0fc56a..13610982 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpMessageRouterTest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpMessageRouterTest.java @@ -5,9 +5,8 @@ import me.chanjar.weixin.common.session.StandardSessionManager; import me.chanjar.weixin.common.session.WxSessionManager; import me.chanjar.weixin.cp.bean.WxCpXmlMessage; import me.chanjar.weixin.cp.bean.WxCpXmlOutMessage; -import org.testng.Assert; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.testng.*; +import org.testng.annotations.*; import java.util.Map; @@ -22,33 +21,33 @@ public class WxCpMessageRouterTest { @Test(enabled = false) public void prepare(boolean async, StringBuffer sb, WxCpMessageRouter router) { router - .rule() - .async(async) - .msgType(WxConsts.XML_MSG_TEXT).event(WxConsts.EVT_CLICK).eventKey("KEY_1").content("CONTENT_1") - .handler(new WxEchoCpMessageHandler(sb, "COMBINE_4")) - .end() - .rule() - .async(async) - .msgType(WxConsts.XML_MSG_TEXT).event(WxConsts.EVT_CLICK).eventKey("KEY_1") - .handler(new WxEchoCpMessageHandler(sb, "COMBINE_3")) - .end() - .rule() - .async(async) - .msgType(WxConsts.XML_MSG_TEXT).event(WxConsts.EVT_CLICK) - .handler(new WxEchoCpMessageHandler(sb, "COMBINE_2")) - .end() - .rule().async(async).msgType(WxConsts.XML_MSG_TEXT).handler(new WxEchoCpMessageHandler(sb, WxConsts.XML_MSG_TEXT)).end() - .rule().async(async).event(WxConsts.EVT_CLICK).handler(new WxEchoCpMessageHandler(sb, WxConsts.EVT_CLICK)).end() - .rule().async(async).eventKey("KEY_1").handler(new WxEchoCpMessageHandler(sb, "KEY_1")).end() - .rule().async(async).content("CONTENT_1").handler(new WxEchoCpMessageHandler(sb, "CONTENT_1")).end() - .rule().async(async).rContent(".*bc.*").handler(new WxEchoCpMessageHandler(sb, "abcd")).end() - .rule().async(async).matcher(new WxCpMessageMatcher() { + .rule() + .async(async) + .msgType(WxConsts.XML_MSG_TEXT).event(WxConsts.EVT_CLICK).eventKey("KEY_1").content("CONTENT_1") + .handler(new WxEchoCpMessageHandler(sb, "COMBINE_4")) + .end() + .rule() + .async(async) + .msgType(WxConsts.XML_MSG_TEXT).event(WxConsts.EVT_CLICK).eventKey("KEY_1") + .handler(new WxEchoCpMessageHandler(sb, "COMBINE_3")) + .end() + .rule() + .async(async) + .msgType(WxConsts.XML_MSG_TEXT).event(WxConsts.EVT_CLICK) + .handler(new WxEchoCpMessageHandler(sb, "COMBINE_2")) + .end() + .rule().async(async).msgType(WxConsts.XML_MSG_TEXT).handler(new WxEchoCpMessageHandler(sb, WxConsts.XML_MSG_TEXT)).end() + .rule().async(async).event(WxConsts.EVT_CLICK).handler(new WxEchoCpMessageHandler(sb, WxConsts.EVT_CLICK)).end() + .rule().async(async).eventKey("KEY_1").handler(new WxEchoCpMessageHandler(sb, "KEY_1")).end() + .rule().async(async).content("CONTENT_1").handler(new WxEchoCpMessageHandler(sb, "CONTENT_1")).end() + .rule().async(async).rContent(".*bc.*").handler(new WxEchoCpMessageHandler(sb, "abcd")).end() + .rule().async(async).matcher(new WxCpMessageMatcher() { @Override public boolean match(WxCpXmlMessage message) { return "strangeformat".equals(message.getFormat()); } }).handler(new WxEchoCpMessageHandler(sb, "matcher")).end() - .rule().async(async).handler(new WxEchoCpMessageHandler(sb, "ALL")).end(); + .rule().async(async).handler(new WxEchoCpMessageHandler(sb, "ALL")).end(); } @Test(dataProvider = "messages-1") @@ -138,16 +137,16 @@ public class WxCpMessageRouterTest { return new Object[][]{ - new Object[]{message1, WxConsts.XML_MSG_TEXT + ","}, - new Object[]{message2, WxConsts.EVT_CLICK + ","}, - new Object[]{message3, "KEY_1,"}, - new Object[]{message4, "CONTENT_1,"}, - new Object[]{message5, "ALL,"}, - new Object[]{message6, "abcd,"}, - new Object[]{message7, "matcher,"}, - new Object[]{c2, "COMBINE_2,"}, - new Object[]{c3, "COMBINE_3,"}, - new Object[]{c4, "COMBINE_4,"} + new Object[]{message1, WxConsts.XML_MSG_TEXT + ","}, + new Object[]{message2, WxConsts.EVT_CLICK + ","}, + new Object[]{message3, "KEY_1,"}, + new Object[]{message4, "CONTENT_1,"}, + new Object[]{message5, "ALL,"}, + new Object[]{message6, "abcd,"}, + new Object[]{message7, "matcher,"}, + new Object[]{c2, "COMBINE_2,"}, + new Object[]{c3, "COMBINE_3,"}, + new Object[]{c4, "COMBINE_4,"} }; } @@ -162,7 +161,7 @@ public class WxCpMessageRouterTest { ism.setBackgroundProcessorDelay(1); return new Object[][]{ - new Object[]{ism} + new Object[]{ism} }; } @@ -174,8 +173,8 @@ public class WxCpMessageRouterTest { final WxCpMessageRouter router = new WxCpMessageRouter(null); router.setSessionManager(ism); router - .rule().async(false).handler(new WxSessionMessageHandler()).next() - .rule().async(false).handler(new WxSessionMessageHandler()).end(); + .rule().async(false).handler(new WxSessionMessageHandler()).next() + .rule().async(false).handler(new WxSessionMessageHandler()).end(); WxCpXmlMessage msg = new WxCpXmlMessage(); msg.setFromUserName("abc"); @@ -194,8 +193,8 @@ public class WxCpMessageRouterTest { final WxCpMessageRouter router = new WxCpMessageRouter(null); router.setSessionManager(ism); router - .rule().async(false).handler(new WxSessionMessageHandler()).next() - .rule().async(true).handler(new WxSessionMessageHandler()).end(); + .rule().async(false).handler(new WxSessionMessageHandler()).next() + .rule().async(true).handler(new WxSessionMessageHandler()).end(); WxCpXmlMessage msg = new WxCpXmlMessage(); msg.setFromUserName("abc"); @@ -208,8 +207,8 @@ public class WxCpMessageRouterTest { final WxCpMessageRouter router = new WxCpMessageRouter(null); router.setSessionManager(ism); router - .rule().async(true).handler(new WxSessionMessageHandler()).next() - .rule().async(false).handler(new WxSessionMessageHandler()).end(); + .rule().async(true).handler(new WxSessionMessageHandler()).next() + .rule().async(false).handler(new WxSessionMessageHandler()).end(); WxCpXmlMessage msg = new WxCpXmlMessage(); msg.setFromUserName("abc"); @@ -228,8 +227,8 @@ public class WxCpMessageRouterTest { final WxCpMessageRouter router = new WxCpMessageRouter(null); router.setSessionManager(ism); router - .rule().async(true).handler(new WxSessionMessageHandler()).next() - .rule().async(true).handler(new WxSessionMessageHandler()).end(); + .rule().async(true).handler(new WxSessionMessageHandler()).next() + .rule().async(true).handler(new WxSessionMessageHandler()).end(); WxCpXmlMessage msg = new WxCpXmlMessage(); msg.setFromUserName("abc"); @@ -248,7 +247,7 @@ public class WxCpMessageRouterTest { final WxCpMessageRouter router = new WxCpMessageRouter(null); router.setSessionManager(ism); router - .rule().async(false).handler(new WxSessionMessageHandler()).end(); + .rule().async(false).handler(new WxSessionMessageHandler()).end(); WxCpXmlMessage msg = new WxCpXmlMessage(); msg.setFromUserName("abc"); @@ -262,7 +261,7 @@ public class WxCpMessageRouterTest { final WxCpMessageRouter router = new WxCpMessageRouter(null); router.setSessionManager(ism); router - .rule().async(true).handler(new WxSessionMessageHandler()).end(); + .rule().async(true).handler(new WxSessionMessageHandler()).end(); WxCpXmlMessage msg = new WxCpXmlMessage(); msg.setFromUserName("abc"); diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpTagAPITest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpTagAPITest.java index d5ff3a3a..170f386c 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpTagAPITest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpTagAPITest.java @@ -4,9 +4,8 @@ import com.google.inject.Inject; import me.chanjar.weixin.cp.api.impl.apache.WxCpServiceImpl; import me.chanjar.weixin.cp.bean.WxCpTag; import me.chanjar.weixin.cp.bean.WxCpUser; -import org.testng.Assert; -import org.testng.annotations.Guice; -import org.testng.annotations.Test; +import org.testng.*; +import org.testng.annotations.*; import java.util.ArrayList; import java.util.List; diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpUserAPITest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpUserAPITest.java index 450cefa2..1bfb7c60 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpUserAPITest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpUserAPITest.java @@ -5,9 +5,8 @@ import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.cp.api.impl.apache.WxCpServiceImpl; import me.chanjar.weixin.cp.bean.WxCpDepart; import me.chanjar.weixin.cp.bean.WxCpUser; -import org.testng.Assert; -import org.testng.annotations.Guice; -import org.testng.annotations.Test; +import org.testng.*; +import org.testng.annotations.*; import java.util.List; diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxMenuAPITest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxMenuAPITest.java index a6fdfa9d..cdeeadf2 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxMenuAPITest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxMenuAPITest.java @@ -6,10 +6,8 @@ import me.chanjar.weixin.common.bean.menu.WxMenu; import me.chanjar.weixin.common.bean.menu.WxMenuButton; import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.cp.api.impl.apache.WxCpServiceImpl; -import org.testng.Assert; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Guice; -import org.testng.annotations.Test; +import org.testng.*; +import org.testng.annotations.*; /** * 测试菜单 @@ -78,9 +76,9 @@ public class WxMenuAPITest { button3.getSubButtons().add(button33); return new Object[][]{ - new Object[]{ - menu - } + new Object[]{ + menu + } }; } diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/apache/WxCpBaseAPITest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/apache/WxCpBaseAPITest.java index 7ed63b77..b3271dc8 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/apache/WxCpBaseAPITest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/apache/WxCpBaseAPITest.java @@ -5,9 +5,8 @@ import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.cp.api.ApiTestModule; import me.chanjar.weixin.cp.api.WxCpConfigStorage; import org.apache.commons.lang3.StringUtils; -import org.testng.Assert; -import org.testng.annotations.Guice; -import org.testng.annotations.Test; +import org.testng.*; +import org.testng.annotations.*; /** * 基础API测试 diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/apache/WxCpBusyRetryTest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/apache/WxCpBusyRetryTest.java index 724368e8..3b8e8fa3 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/apache/WxCpBusyRetryTest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/apache/WxCpBusyRetryTest.java @@ -4,8 +4,7 @@ import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.common.util.http.RequestExecutor; import me.chanjar.weixin.cp.api.WxCpService; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.testng.annotations.*; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; @@ -22,7 +21,7 @@ public class WxCpBusyRetryTest { @Override public synchronized T executeInternal( RequestExecutor executor, String uri, E data) - throws WxErrorException { + throws WxErrorException { this.log.info("Executed"); WxError error = new WxError(); error.setErrorCode(-1); @@ -33,7 +32,7 @@ public class WxCpBusyRetryTest { service.setMaxRetryTimes(3); service.setRetrySleepMillis(500); return new Object[][]{ - new Object[]{service} + new Object[]{service} }; } diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/apache/WxCpMessageAPITest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/apache/WxCpMessageAPITest.java index 470323f2..d6004dee 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/apache/WxCpMessageAPITest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/apache/WxCpMessageAPITest.java @@ -5,8 +5,7 @@ import me.chanjar.weixin.common.api.WxConsts; import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.cp.api.ApiTestModule; import me.chanjar.weixin.cp.bean.WxCpMessage; -import org.testng.annotations.Guice; -import org.testng.annotations.Test; +import org.testng.annotations.*; /*** * 测试发送消息 @@ -30,11 +29,11 @@ public class WxCpMessageAPITest { this.wxService.messageSend(message1); WxCpMessage message2 = WxCpMessage - .TEXT() - .agentId(configStorage.getAgentId()) - .toUser(configStorage.getUserId()) - .content("欢迎欢迎,热烈欢迎\n换行测试\n超链接:Hello World") - .build(); + .TEXT() + .agentId(configStorage.getAgentId()) + .toUser(configStorage.getUserId()) + .content("欢迎欢迎,热烈欢迎\n换行测试\n超链接:Hello World") + .build(); this.wxService.messageSend(message2); } diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpMessageTest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpMessageTest.java index ce75b066..cb3d2cdd 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpMessageTest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpMessageTest.java @@ -1,12 +1,11 @@ package me.chanjar.weixin.cp.bean; import me.chanjar.weixin.common.api.WxConsts; -import me.chanjar.weixin.cp.bean.article.NewArticle; import me.chanjar.weixin.cp.bean.article.MpnewsArticle; -import org.testng.Assert; -import org.testng.annotations.Test; +import me.chanjar.weixin.cp.bean.article.NewArticle; +import org.testng.annotations.*; -import static org.testng.Assert.assertEquals; +import static org.testng.Assert.*; @Test public class WxCpMessageTest { diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlMessageTest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlMessageTest.java index 270fa1d3..9a6eedf1 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlMessageTest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlMessageTest.java @@ -1,8 +1,8 @@ package me.chanjar.weixin.cp.bean; import me.chanjar.weixin.common.api.WxConsts; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.testng.*; +import org.testng.annotations.*; @Test public class WxCpXmlMessageTest { @@ -10,49 +10,49 @@ public class WxCpXmlMessageTest { public void testFromXml() { String xml = "" - + "" - + " " - + "1348831860" - + "" - + "" - + "1234567890123456" - + "" - + "" - + "" - + "" - + "23.134521" - + "113.358803" - + "20" - + "" - + "" - + "" - + "<![CDATA[公众平台官网链接]]>" - + "" - + "" - + "" - + "23.137466" - + "113.352425" - + "119.385040" - + "" - + " " - + " " - + "" - + "" - + " 1\n" - + " " - + " " - + " " - + " " - + " " - + "" - + "" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + "" - + ""; + + "" + + " " + + "1348831860" + + "" + + "" + + "1234567890123456" + + "" + + "" + + "" + + "" + + "23.134521" + + "113.358803" + + "20" + + "" + + "" + + "" + + "<![CDATA[公众平台官网链接]]>" + + "" + + "" + + "" + + "23.137466" + + "113.352425" + + "119.385040" + + "" + + " " + + " " + + "" + + "" + + " 1\n" + + " " + + " " + + " " + + " " + + " " + + "" + + "" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + ""; WxCpXmlMessage wxMessage = WxCpXmlMessage.fromXml(xml); Assert.assertEquals(wxMessage.getToUserName(), "toUser"); Assert.assertEquals(wxMessage.getFromUserName(), "fromUser"); diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutImageMessageTest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutImageMessageTest.java index 8ace5d0a..26602434 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutImageMessageTest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutImageMessageTest.java @@ -1,7 +1,7 @@ package me.chanjar.weixin.cp.bean; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.testng.*; +import org.testng.annotations.*; @Test public class WxCpXmlOutImageMessageTest { @@ -14,12 +14,12 @@ public class WxCpXmlOutImageMessageTest { m.setToUserName("to"); String expected = "" - + "" - + "" - + "1122" - + "" - + "" - + ""; + + "" + + "" + + "1122" + + "" + + "" + + ""; System.out.println(m.toXml()); Assert.assertEquals(m.toXml().replaceAll("\\s", ""), expected.replaceAll("\\s", "")); } @@ -27,21 +27,21 @@ public class WxCpXmlOutImageMessageTest { public void testBuild() { WxCpXmlOutImageMessage m = WxCpXmlOutMessage.IMAGE().mediaId("ddfefesfsdfef").fromUser("from").toUser("to").build(); String expected = "" - + "" - + "" - + "1122" - + "" - + "" - + ""; + + "" + + "" + + "1122" + + "" + + "" + + ""; System.out.println(m.toXml()); Assert.assertEquals( - m - .toXml() - .replaceAll("\\s", "") - .replaceAll(".*?", ""), - expected - .replaceAll("\\s", "") - .replaceAll(".*?", "") + m + .toXml() + .replaceAll("\\s", "") + .replaceAll(".*?", ""), + expected + .replaceAll("\\s", "") + .replaceAll(".*?", "") ); } diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutNewsMessageTest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutNewsMessageTest.java index 872c0ac3..2013e7a3 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutNewsMessageTest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutNewsMessageTest.java @@ -1,7 +1,7 @@ package me.chanjar.weixin.cp.bean; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.testng.*; +import org.testng.annotations.*; @Test public class WxCpXmlOutNewsMessageTest { @@ -21,26 +21,26 @@ public class WxCpXmlOutNewsMessageTest { m.addArticle(item); String expected = "" - + "" - + "" - + "1122" - + "" - + " " - + " " - + " <![CDATA[title]]>" - + " " - + " " - + " " - + " " - + " " - + " <![CDATA[title]]>" - + " " - + " " - + " " - + " " - + " " - + " 2" - + ""; + + "" + + "" + + "1122" + + "" + + " " + + " " + + " <![CDATA[title]]>" + + " " + + " " + + " " + + " " + + " " + + " <![CDATA[title]]>" + + " " + + " " + + " " + + " " + + " " + + " 2" + + ""; System.out.println(m.toXml()); Assert.assertEquals(m.toXml().replaceAll("\\s", ""), expected.replaceAll("\\s", "")); } @@ -53,41 +53,41 @@ public class WxCpXmlOutNewsMessageTest { item.setUrl("url"); WxCpXmlOutNewsMessage m = WxCpXmlOutMessage.NEWS() - .fromUser("fromUser") - .toUser("toUser") - .addArticle(item) - .addArticle(item) - .build(); + .fromUser("fromUser") + .toUser("toUser") + .addArticle(item) + .addArticle(item) + .build(); String expected = "" - + "" - + "" - + "1122" - + "" - + " " - + " " - + " <![CDATA[title]]>" - + " " - + " " - + " " - + " " - + " " - + " <![CDATA[title]]>" - + " " - + " " - + " " - + " " - + " " - + " 2" - + ""; + + "" + + "" + + "1122" + + "" + + " " + + " " + + " <![CDATA[title]]>" + + " " + + " " + + " " + + " " + + " " + + " <![CDATA[title]]>" + + " " + + " " + + " " + + " " + + " " + + " 2" + + ""; System.out.println(m.toXml()); Assert.assertEquals( - m - .toXml() - .replaceAll("\\s", "") - .replaceAll(".*?", ""), - expected - .replaceAll("\\s", "") - .replaceAll(".*?", "") + m + .toXml() + .replaceAll("\\s", "") + .replaceAll(".*?", ""), + expected + .replaceAll("\\s", "") + .replaceAll(".*?", "") ); } diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutTextMessageTest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutTextMessageTest.java index 57fcf8eb..975eb5d1 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutTextMessageTest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutTextMessageTest.java @@ -1,7 +1,7 @@ package me.chanjar.weixin.cp.bean; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.testng.*; +import org.testng.annotations.*; @Test public class WxCpXmlOutTextMessageTest { @@ -14,12 +14,12 @@ public class WxCpXmlOutTextMessageTest { m.setToUserName("to"); String expected = "" - + "" - + "" - + "1122" - + "" - + "" - + ""; + + "" + + "" + + "1122" + + "" + + "" + + ""; System.out.println(m.toXml()); Assert.assertEquals(m.toXml().replaceAll("\\s", ""), expected.replaceAll("\\s", "")); } @@ -27,21 +27,21 @@ public class WxCpXmlOutTextMessageTest { public void testBuild() { WxCpXmlOutTextMessage m = WxCpXmlOutMessage.TEXT().content("content").fromUser("from").toUser("to").build(); String expected = "" - + "" - + "" - + "1122" - + "" - + "" - + ""; + + "" + + "" + + "1122" + + "" + + "" + + ""; System.out.println(m.toXml()); Assert.assertEquals( - m - .toXml() - .replaceAll("\\s", "") - .replaceAll(".*?", ""), - expected - .replaceAll("\\s", "") - .replaceAll(".*?", "") + m + .toXml() + .replaceAll("\\s", "") + .replaceAll(".*?", ""), + expected + .replaceAll("\\s", "") + .replaceAll(".*?", "") ); } diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVideoMessageTest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVideoMessageTest.java index 512dfef3..5ad42ba7 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVideoMessageTest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVideoMessageTest.java @@ -1,7 +1,7 @@ package me.chanjar.weixin.cp.bean; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.testng.*; +import org.testng.annotations.*; @Test public class WxCpXmlOutVideoMessageTest { @@ -16,48 +16,48 @@ public class WxCpXmlOutVideoMessageTest { m.setToUserName("toUser"); String expected = "" - + "" - + "" - + "1122" - + "" - + " " - + ""; + + "" + + "" + + "1122" + + "" + + " " + + ""; System.out.println(m.toXml()); Assert.assertEquals(m.toXml().replaceAll("\\s", ""), expected.replaceAll("\\s", "")); } public void testBuild() { WxCpXmlOutVideoMessage m = WxCpXmlOutMessage.VIDEO() - .mediaId("media_id") - .fromUser("fromUser") - .toUser("toUser") - .title("title") - .description("ddfff") - .build(); + .mediaId("media_id") + .fromUser("fromUser") + .toUser("toUser") + .title("title") + .description("ddfff") + .build(); String expected = "" - + "" - + "" - + "1122" - + "" - + " " - + ""; + + "" + + "" + + "1122" + + "" + + " " + + ""; System.out.println(m.toXml()); Assert.assertEquals( - m - .toXml() - .replaceAll("\\s", "") - .replaceAll(".*?", ""), - expected - .replaceAll("\\s", "") - .replaceAll(".*?", "") + m + .toXml() + .replaceAll("\\s", "") + .replaceAll(".*?", ""), + expected + .replaceAll("\\s", "") + .replaceAll(".*?", "") ); } diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVoiceMessageTest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVoiceMessageTest.java index 26db29c3..29379601 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVoiceMessageTest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVoiceMessageTest.java @@ -1,7 +1,7 @@ package me.chanjar.weixin.cp.bean; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.testng.*; +import org.testng.annotations.*; @Test public class WxCpXmlOutVoiceMessageTest { @@ -14,12 +14,12 @@ public class WxCpXmlOutVoiceMessageTest { m.setToUserName("to"); String expected = "" - + "" - + "" - + "1122" - + "" - + "" - + ""; + + "" + + "" + + "1122" + + "" + + "" + + ""; System.out.println(m.toXml()); Assert.assertEquals(m.toXml().replaceAll("\\s", ""), expected.replaceAll("\\s", "")); } @@ -27,21 +27,21 @@ public class WxCpXmlOutVoiceMessageTest { public void testBuild() { WxCpXmlOutVoiceMessage m = WxCpXmlOutMessage.VOICE().mediaId("ddfefesfsdfef").fromUser("from").toUser("to").build(); String expected = "" - + "" - + "" - + "1122" - + "" - + "" - + ""; + + "" + + "" + + "1122" + + "" + + "" + + ""; System.out.println(m.toXml()); Assert.assertEquals( - m - .toXml() - .replaceAll("\\s", "") - .replaceAll(".*?", ""), - expected - .replaceAll("\\s", "") - .replaceAll(".*?", "") + m + .toXml() + .replaceAll("\\s", "") + .replaceAll(".*?", ""), + expected + .replaceAll("\\s", "") + .replaceAll(".*?", "") ); } diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpDemoInMemoryConfigStorage.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpDemoInMemoryConfigStorage.java index 9a97b6cd..4171119b 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpDemoInMemoryConfigStorage.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpDemoInMemoryConfigStorage.java @@ -22,7 +22,7 @@ class WxCpDemoInMemoryConfigStorage extends WxCpInMemoryConfigStorage { @Override public String toString() { return "SimpleWxConfigProvider [appidOrCorpid=" + this.corpId + ", corpSecret=" + this.corpSecret + ", accessToken=" + this.accessToken - + ", expiresTime=" + this.expiresTime + ", token=" + this.token + ", aesKey=" + this.aesKey + "]"; + + ", expiresTime=" + this.expiresTime + ", token=" + this.token + ", aesKey=" + this.aesKey + "]"; } } diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpDemoServer.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpDemoServer.java index eb78d667..6862347b 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpDemoServer.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpDemoServer.java @@ -1,13 +1,5 @@ package me.chanjar.weixin.cp.demo; -import java.io.IOException; -import java.io.InputStream; -import java.util.Map; - -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; - import me.chanjar.weixin.common.session.WxSessionManager; import me.chanjar.weixin.cp.api.WxCpConfigStorage; import me.chanjar.weixin.cp.api.WxCpMessageHandler; @@ -17,6 +9,13 @@ import me.chanjar.weixin.cp.api.impl.apache.WxCpServiceImpl; import me.chanjar.weixin.cp.bean.WxCpXmlMessage; import me.chanjar.weixin.cp.bean.WxCpXmlOutMessage; import me.chanjar.weixin.cp.bean.WxCpXmlOutTextMessage; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.servlet.ServletHandler; +import org.eclipse.jetty.servlet.ServletHolder; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Map; public class WxCpDemoServer { @@ -44,9 +43,9 @@ public class WxCpDemoServer { private static void initWeixin() throws IOException { try (InputStream is1 = ClassLoader - .getSystemResourceAsStream("test-config.xml")) { + .getSystemResourceAsStream("test-config.xml")) { WxCpDemoInMemoryConfigStorage config = WxCpDemoInMemoryConfigStorage - .fromXml(is1); + .fromXml(is1); wxCpConfigStorage = config; wxCpService = new WxCpServiceImpl(); @@ -55,11 +54,11 @@ public class WxCpDemoServer { WxCpMessageHandler handler = new WxCpMessageHandler() { @Override public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage, - Map context, WxCpService wxService, - WxSessionManager sessionManager) { + Map context, WxCpService wxService, + WxSessionManager sessionManager) { WxCpXmlOutTextMessage m = WxCpXmlOutMessage.TEXT().content("测试加密消息") - .fromUser(wxMessage.getToUserName()) - .toUser(wxMessage.getFromUserName()).build(); + .fromUser(wxMessage.getToUserName()) + .toUser(wxMessage.getFromUserName()).build(); return m; } }; @@ -67,22 +66,22 @@ public class WxCpDemoServer { WxCpMessageHandler oauth2handler = new WxCpMessageHandler() { @Override public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage, - Map context, WxCpService wxService, - WxSessionManager sessionManager) { + Map context, WxCpService wxService, + WxSessionManager sessionManager) { String href = "测试oauth2"; + + wxService.oauth2buildAuthorizationUrl( + wxCpConfigStorage.getOauth2redirectUri(), null) + + "\">测试oauth2"; return WxCpXmlOutMessage.TEXT().content(href) - .fromUser(wxMessage.getToUserName()) - .toUser(wxMessage.getFromUserName()).build(); + .fromUser(wxMessage.getToUserName()) + .toUser(wxMessage.getFromUserName()).build(); } }; wxCpMessageRouter = new WxCpMessageRouter(wxCpService); wxCpMessageRouter.rule().async(false).content("哈哈") // 拦截内容为“哈哈”的消息 - .handler(handler).end().rule().async(false).content("oauth") - .handler(oauth2handler).end(); + .handler(handler).end().rule().async(false).content("oauth") + .handler(oauth2handler).end(); } } diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpEndpointServlet.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpEndpointServlet.java index 43bf1799..dec6faee 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpEndpointServlet.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpEndpointServlet.java @@ -31,7 +31,7 @@ public class WxCpEndpointServlet extends HttpServlet { @Override protected void service(HttpServletRequest request, HttpServletResponse response) - throws IOException { + throws IOException { response.setContentType("text/html;charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); @@ -55,7 +55,7 @@ public class WxCpEndpointServlet extends HttpServlet { } WxCpXmlMessage inMessage = WxCpXmlMessage - .fromEncryptedXml(request.getInputStream(), this.wxCpConfigStorage, timestamp, nonce, msgSignature); + .fromEncryptedXml(request.getInputStream(), this.wxCpConfigStorage, timestamp, nonce, msgSignature); WxCpXmlOutMessage outMessage = this.wxCpMessageRouter.route(inMessage); if (outMessage != null) { response.getWriter().write(outMessage.toEncryptedXml(this.wxCpConfigStorage)); diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpOAuth2Servlet.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpOAuth2Servlet.java index edab8966..d65e2427 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpOAuth2Servlet.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpOAuth2Servlet.java @@ -1,14 +1,13 @@ package me.chanjar.weixin.cp.demo; -import java.io.IOException; -import java.util.Arrays; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.cp.api.WxCpService; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - -import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.cp.api.WxCpService; +import java.io.IOException; +import java.util.Arrays; public class WxCpOAuth2Servlet extends HttpServlet { private static final long serialVersionUID = 1L; @@ -21,7 +20,7 @@ public class WxCpOAuth2Servlet extends HttpServlet { @Override protected void service(HttpServletRequest request, HttpServletResponse response) - throws IOException { + throws IOException { response.setContentType("text/html;charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); diff --git a/weixin-java-cp/src/test/resources/logback-test.xml b/weixin-java-cp/src/test/resources/logback-test.xml index 9c2ec6ae..998a6896 100644 --- a/weixin-java-cp/src/test/resources/logback-test.xml +++ b/weixin-java-cp/src/test/resources/logback-test.xml @@ -9,8 +9,8 @@ - + - + diff --git a/weixin-java-cp/src/test/resources/test-config.sample.xml b/weixin-java-cp/src/test/resources/test-config.sample.xml index aa99a962..6f98ebaf 100644 --- a/weixin-java-cp/src/test/resources/test-config.sample.xml +++ b/weixin-java-cp/src/test/resources/test-config.sample.xml @@ -1,13 +1,13 @@ - 企业号corpid - 企业号corpsecret - 企业号应用id - 企业号应用Token - 企业号应用EncodingAESKey - 可以不填写 - 可以不填写 - 企业号通讯录里的某个userid - 企业号通讯录的某个部门id - 企业号通讯录里的某个tagid - 网页授权获取用户信息回调地址 + 企业号corpid + 企业号corpsecret + 企业号应用id + 企业号应用Token + 企业号应用EncodingAESKey + 可以不填写 + 可以不填写 + 企业号通讯录里的某个userid + 企业号通讯录的某个部门id + 企业号通讯录里的某个tagid + 网页授权获取用户信息回调地址 diff --git a/weixin-java-mp/build.gradle b/weixin-java-mp/build.gradle index de1534a3..bd91f2f8 100644 --- a/weixin-java-mp/build.gradle +++ b/weixin-java-mp/build.gradle @@ -1,13 +1,12 @@ - description = 'WeiXin Java Tools - MP' dependencies { compile project(':weixin-java-common') - testCompile group: 'junit', name: 'junit', version:'4.11' - testCompile group: 'org.testng', name: 'testng', version:'6.8.7' - testCompile group: 'org.mockito', name: 'mockito-all', version:'1.9.5' - testCompile group: 'com.google.inject', name: 'guice', version:'3.0' - testCompile group: 'org.eclipse.jetty', name: 'jetty-server', version:'9.3.0.RC0' - testCompile group: 'org.eclipse.jetty', name: 'jetty-servlet', version:'9.3.0.RC0' - testCompile group: 'joda-time', name: 'joda-time', version:'2.9.4' + testCompile group: 'junit', name: 'junit', version: '4.11' + testCompile group: 'org.testng', name: 'testng', version: '6.8.7' + testCompile group: 'org.mockito', name: 'mockito-all', version: '1.9.5' + testCompile group: 'com.google.inject', name: 'guice', version: '3.0' + testCompile group: 'org.eclipse.jetty', name: 'jetty-server', version: '9.3.0.RC0' + testCompile group: 'org.eclipse.jetty', name: 'jetty-servlet', version: '9.3.0.RC0' + testCompile group: 'joda-time', name: 'joda-time', version: '2.9.4' } test.useTestNG() diff --git a/weixin-java-mp/pom.xml b/weixin-java-mp/pom.xml index e736d4c2..1b97c008 100644 --- a/weixin-java-mp/pom.xml +++ b/weixin-java-mp/pom.xml @@ -1,7 +1,8 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" + xmlns="http://maven.apache.org/POM/4.0.0"> 4.0.0 com.github.binarywang diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpCardService.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpCardService.java index 715c3936..c1327776 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpCardService.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpCardService.java @@ -6,6 +6,7 @@ import me.chanjar.weixin.mp.bean.result.WxMpCardResult; /** * 卡券相关接口 + * * @author YuJian(mgcnrx11@hotmail.com) on 01/11/2016 */ public interface WxMpCardService { @@ -52,7 +53,7 @@ public interface WxMpCardService { * @return 卡券Api签名对象 */ WxCardApiSignature createCardApiSignature(String... optionalSignParam) throws - WxErrorException; + WxErrorException; /** * 卡券Code解码 @@ -71,7 +72,7 @@ public interface WxMpCardService { * @return WxMpCardResult对象 */ WxMpCardResult queryCardCode(String cardId, String code, boolean checkConsume) - throws WxErrorException; + throws WxErrorException; /** * 卡券Code核销。核销失败会抛出异常 @@ -103,7 +104,7 @@ public interface WxMpCardService { * @param isMark 是否要mark(占用)这个code,填写true或者false,表示占用或解除占用 */ void markCardCode(String code, String cardId, String openId, boolean isMark) throws - WxErrorException; + WxErrorException; /** * 查看卡券详情接口 diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpDataCubeService.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpDataCubeService.java index 32f219d5..64484433 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpDataCubeService.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpDataCubeService.java @@ -1,19 +1,15 @@ package me.chanjar.weixin.mp.api; import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.mp.bean.datacube.WxDataCubeArticleResult; -import me.chanjar.weixin.mp.bean.datacube.WxDataCubeArticleTotal; -import me.chanjar.weixin.mp.bean.datacube.WxDataCubeInterfaceResult; -import me.chanjar.weixin.mp.bean.datacube.WxDataCubeMsgResult; -import me.chanjar.weixin.mp.bean.datacube.WxDataCubeUserCumulate; -import me.chanjar.weixin.mp.bean.datacube.WxDataCubeUserSummary; +import me.chanjar.weixin.mp.bean.datacube.*; import java.util.Date; import java.util.List; /** * 统计分析相关接口 - * Created by Binary Wang on 2016/8/23. + * Created by Binary Wang on 2016/8/23. + * * @author binarywang (https://github.com/binarywang) */ public interface WxMpDataCubeService { @@ -192,6 +188,7 @@ public interface WxMpDataCubeService { List getUpstreamMsgDistMonth(Date beginDate, Date endDate) throws WxErrorException; //*******************接口分析数据接口***********************// + /** *

        * 获取接口分析数据(getinterfacesummary)
    diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpDeviceService.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpDeviceService.java
    index 2580d23a..6b3fcd9e 100644
    --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpDeviceService.java
    +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpDeviceService.java
    @@ -20,6 +20,7 @@ public interface WxMpDeviceService {
        *   获取一组新的deviceid和设备二维码
        *   详情请见:http://iot.weixin.qq.com/wiki/new/index.html?page=3-4-6
        * 
    + * * @param productId 产品id * @return 返回WxDeviceQrCodeResult */ @@ -30,6 +31,7 @@ public interface WxMpDeviceService { * 将device id及其属性信息提交公众平台进行授权 * 详情请见:http://iot.weixin.qq.com/wiki/new/index.html?page=3-4-6 *
    + * * @param wxDeviceAuthorize 授权请求对象 * @return WxDeviceAuthorizeResult */ @@ -41,6 +43,7 @@ public interface WxMpDeviceService { * 第三方后台绑定成功后,通知公众平台 * 详情请见:http://iot.weixin.qq.com/wiki/new/index.html/page=3-4-7 *
    + * * @param wxDeviceBind 绑定请求对象 * @return WxDeviceBindResult */ @@ -51,6 +54,7 @@ public interface WxMpDeviceService { * 强制绑定用户和设备 * 详情请见:http://iot.weixin.qq.com/wiki/new/index.html?page=3-4-7 * + * * @param wxDeviceBind 强制绑定请求对象 * @return WxDeviceBindResult */ @@ -61,6 +65,7 @@ public interface WxMpDeviceService { * 第三方确认用户和设备的解绑操作 * 详情请见:http://iot.weixin.qq.com/wiki/new/index.html/page=3-4-7 * + * * @param wxDeviceBind 绑定请求对象 * @return WxDeviceBidResult */ @@ -71,6 +76,7 @@ public interface WxMpDeviceService { * 强制解绑用户和设备 * 详情请见:http://iot.weixin.qq.com/wiki/new/index.html?page=3-4-7 * + * * @param wxDeviceBind 强制解绑请求对象 * @return WxDeviceBindResult */ @@ -81,17 +87,19 @@ public interface WxMpDeviceService { * 通过device type和device id 获取设备主人的openid * 详情请见:http://iot.weixin.qq.com/wiki/new/index.html?page=3-4-11 * + * * @param deviceType 设备类型,目前为"公众账号原始ID" - * @param deviceId 设备ID + * @param deviceId 设备ID * @return WxDeviceOpenIdResult */ - WxDeviceOpenIdResult getOpenId(String deviceType,String deviceId) throws WxErrorException; + WxDeviceOpenIdResult getOpenId(String deviceType, String deviceId) throws WxErrorException; /** *
        *   通过openid获取用户在当前devicetype下绑定的deviceid列表`
        *   详情请见:http://iot.weixin.qq.com/wiki/new/index.html?page=3-4-12
        * 
    + * * @param openId 要查询的用户的openid * @return WxDeviceBindDeviceResult */ diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpInMemoryConfigStorage.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpInMemoryConfigStorage.java index 9181a401..e74f5188 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpInMemoryConfigStorage.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpInMemoryConfigStorage.java @@ -51,6 +51,10 @@ public class WxMpInMemoryConfigStorage implements WxMpConfigStorage { return this.accessToken; } + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + @Override public Lock getAccessTokenLock() { return this.accessTokenLock; @@ -82,6 +86,10 @@ public class WxMpInMemoryConfigStorage implements WxMpConfigStorage { return this.jsapiTicket; } + public void setJsapiTicket(String jsapiTicket) { + this.jsapiTicket = jsapiTicket; + } + @Override public Lock getJsapiTicketLock() { return this.jsapiTicketLock; @@ -112,6 +120,10 @@ public class WxMpInMemoryConfigStorage implements WxMpConfigStorage { return this.cardApiTicket; } + public void setCardApiTicket(String cardApiTicket) { + this.cardApiTicket = cardApiTicket; + } + @Override public Lock getCardApiTicketLock() { return this.cardApiTicketLock; @@ -247,14 +259,6 @@ public class WxMpInMemoryConfigStorage implements WxMpConfigStorage { this.apacheHttpClientBuilder = apacheHttpClientBuilder; } - public void setAccessToken(String accessToken) { - this.accessToken = accessToken; - } - - public void setJsapiTicket(String jsapiTicket) { - this.jsapiTicket = jsapiTicket; - } - public long getJsapiTicketExpiresTime() { return this.jsapiTicketExpiresTime; } @@ -263,10 +267,6 @@ public class WxMpInMemoryConfigStorage implements WxMpConfigStorage { this.jsapiTicketExpiresTime = jsapiTicketExpiresTime; } - public void setCardApiTicket(String cardApiTicket) { - this.cardApiTicket = cardApiTicket; - } - public long getCardApiTicketExpiresTime() { return this.cardApiTicketExpiresTime; } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpInRedisConfigStorage.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpInRedisConfigStorage.java index b2bb9b4e..706d59ec 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpInRedisConfigStorage.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpInRedisConfigStorage.java @@ -25,10 +25,10 @@ public class WxMpInRedisConfigStorage extends WxMpInMemoryConfigStorage { @Override public boolean isAccessTokenExpired() { - return getAccessToken() == null ? true : false; + return getAccessToken() == null ? true : false; } -@Override + @Override public synchronized void updateAccessToken(String accessToken, int expiresInSeconds) { jedis.set(ACCESS_TOKEN_KEY.concat(appId), accessToken); jedis.expire(ACCESS_TOKEN_KEY.concat(appId), expiresInSeconds - 200); @@ -87,4 +87,4 @@ public class WxMpInRedisConfigStorage extends WxMpInMemoryConfigStorage { public void setJedis(Jedis jedis) { this.jedis = jedis; } -} \ No newline at end of file +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpKefuService.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpKefuService.java index 3e74d041..36e13b13 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpKefuService.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpKefuService.java @@ -13,6 +13,7 @@ import java.util.Date; * 客服接口 , * 注意:命名采用kefu拼音的原因是:其英文CustomerService如果再加上Service后缀显得有点啰嗦,如果不加又显得表意不完整。 * + * * @author Binary Wang */ public interface WxMpKefuService { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMaterialService.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMaterialService.java index 8c867c5f..8e769d3e 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMaterialService.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMaterialService.java @@ -2,9 +2,6 @@ package me.chanjar.weixin.mp.api; import me.chanjar.weixin.common.bean.result.WxMediaUploadResult; import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.mp.bean.material.WxMpMaterial; -import me.chanjar.weixin.mp.bean.material.WxMpMaterialArticleUpdate; -import me.chanjar.weixin.mp.bean.material.WxMpMaterialNews; import me.chanjar.weixin.mp.bean.material.*; import java.io.File; @@ -37,12 +34,13 @@ public interface WxMpMaterialService { * 语音(voice):2M,播放长度不超过60s,支持AMR\MP3格式 * 视频(video):10MB,支持MP4格式 * 缩略图(thumb):64KB,支持JPG格式 - *媒体文件在后台保存时间为3天,即3天后media_id失效。 + * 媒体文件在后台保存时间为3天,即3天后media_id失效。 * 详情请见: 新增临时素材 * 接口url格式:https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE * + * * @param mediaType 媒体类型, 请看{@link me.chanjar.weixin.common.api.WxConsts} - * @param file 文件对象 + * @param file 文件对象 * @throws WxErrorException * @see #mediaUpload(String, String, InputStream) */ @@ -106,12 +104,12 @@ public interface WxMpMaterialService { * 接口url格式:https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=ACCESS_TOKEN&type=TYPE * * 除了3天就会失效的临时素材外,开发者有时需要永久保存一些素材,届时就可以通过本接口新增永久素材。 - 永久图片素材新增后,将带有URL返回给开发者,开发者可以在腾讯系域名内使用(腾讯系域名外使用,图片将被屏蔽)。 - 请注意: - 1、新增的永久素材也可以在公众平台官网素材管理模块中看到 - 2、永久素材的数量是有上限的,请谨慎新增。图文消息素材和图片素材的上限为5000,其他类型为1000 - 3、素材的格式大小等要求与公众平台官网一致。具体是,图片大小不超过2M,支持bmp/png/jpeg/jpg/gif格式,语音大小不超过5M,长度不超过60秒,支持mp3/wma/wav/amr格式 - 4、调用该接口需https协议 + * 永久图片素材新增后,将带有URL返回给开发者,开发者可以在腾讯系域名内使用(腾讯系域名外使用,图片将被屏蔽)。 + * 请注意: + * 1、新增的永久素材也可以在公众平台官网素材管理模块中看到 + * 2、永久素材的数量是有上限的,请谨慎新增。图文消息素材和图片素材的上限为5000,其他类型为1000 + * 3、素材的格式大小等要求与公众平台官网一致。具体是,图片大小不超过2M,支持bmp/png/jpeg/jpg/gif格式,语音大小不超过5M,长度不超过60秒,支持mp3/wma/wav/amr格式 + * 4、调用该接口需https协议 * * * @param mediaType 媒体类型, 请看{@link me.chanjar.weixin.common.api.WxConsts} @@ -127,12 +125,12 @@ public interface WxMpMaterialService { * 接口url格式:https://api.weixin.qq.com/cgi-bin/material/add_news?access_token=ACCESS_TOKEN * * 除了3天就会失效的临时素材外,开发者有时需要永久保存一些素材,届时就可以通过本接口新增永久素材。 - 永久图片素材新增后,将带有URL返回给开发者,开发者可以在腾讯系域名内使用(腾讯系域名外使用,图片将被屏蔽)。 - 请注意: - 1、新增的永久素材也可以在公众平台官网素材管理模块中看到 - 2、永久素材的数量是有上限的,请谨慎新增。图文消息素材和图片素材的上限为5000,其他类型为1000 - 3、素材的格式大小等要求与公众平台官网一致。具体是,图片大小不超过2M,支持bmp/png/jpeg/jpg/gif格式,语音大小不超过5M,长度不超过60秒,支持mp3/wma/wav/amr格式 - 4、调用该接口需https协议 + * 永久图片素材新增后,将带有URL返回给开发者,开发者可以在腾讯系域名内使用(腾讯系域名外使用,图片将被屏蔽)。 + * 请注意: + * 1、新增的永久素材也可以在公众平台官网素材管理模块中看到 + * 2、永久素材的数量是有上限的,请谨慎新增。图文消息素材和图片素材的上限为5000,其他类型为1000 + * 3、素材的格式大小等要求与公众平台官网一致。具体是,图片大小不超过2M,支持bmp/png/jpeg/jpg/gif格式,语音大小不超过5M,长度不超过60秒,支持mp3/wma/wav/amr格式 + * 4、调用该接口需https协议 * * * @param news 上传的图文消息, 请看{@link WxMpMaterialNews} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMenuService.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMenuService.java index f1c9fd47..bfd60617 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMenuService.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMenuService.java @@ -19,6 +19,7 @@ public interface WxMpMenuService { * 如果要创建个性化菜单,请设置matchrule属性 * 详情请见:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1455782296&token=&lang=zh_CN * + * * @return 如果是个性化菜单,则返回menuid,否则返回null */ String menuCreate(WxMenu menu) throws WxErrorException; @@ -30,6 +31,7 @@ public interface WxMpMenuService { * 如果要创建个性化菜单,请设置matchrule属性 * 详情请见:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1455782296&token=&lang=zh_CN * + * * @return 如果是个性化菜单,则返回menuid,否则返回null */ String menuCreate(String json) throws WxErrorException; @@ -74,16 +76,16 @@ public interface WxMpMenuService { *
        * 获取自定义菜单配置接口
        * 本接口将会提供公众号当前使用的自定义菜单的配置,如果公众号是通过API调用设置的菜单,则返回菜单的开发配置,而如果公众号是在公众平台官网通过网站功能发布菜单,则本接口返回运营者设置的菜单配置。
    -     请注意:
    -     1、第三方平台开发者可以通过本接口,在旗下公众号将业务授权给你后,立即通过本接口检测公众号的自定义菜单配置,并通过接口再次给公众号设置好自动回复规则,以提升公众号运营者的业务体验。
    -     2、本接口与自定义菜单查询接口的不同之处在于,本接口无论公众号的接口是如何设置的,都能查询到接口,而自定义菜单查询接口则仅能查询到使用API设置的菜单配置。
    -     3、认证/未认证的服务号/订阅号,以及接口测试号,均拥有该接口权限。
    -     4、从第三方平台的公众号登录授权机制上来说,该接口从属于消息与菜单权限集。
    -     5、本接口中返回的图片/语音/视频为临时素材(临时素材每次获取都不同,3天内有效,通过素材管理-获取临时素材接口来获取这些素材),本接口返回的图文消息为永久素材素材(通过素材管理-获取永久素材接口来获取这些素材)。
    +   * 请注意:
    +   * 1、第三方平台开发者可以通过本接口,在旗下公众号将业务授权给你后,立即通过本接口检测公众号的自定义菜单配置,并通过接口再次给公众号设置好自动回复规则,以提升公众号运营者的业务体验。
    +   * 2、本接口与自定义菜单查询接口的不同之处在于,本接口无论公众号的接口是如何设置的,都能查询到接口,而自定义菜单查询接口则仅能查询到使用API设置的菜单配置。
    +   * 3、认证/未认证的服务号/订阅号,以及接口测试号,均拥有该接口权限。
    +   * 4、从第三方平台的公众号登录授权机制上来说,该接口从属于消息与菜单权限集。
    +   * 5、本接口中返回的图片/语音/视频为临时素材(临时素材每次获取都不同,3天内有效,通过素材管理-获取临时素材接口来获取这些素材),本接口返回的图文消息为永久素材素材(通过素材管理-获取永久素材接口来获取这些素材)。
        *  接口调用请求说明:
    -        http请求方式: GET(请使用https协议)
    -        https://api.weixin.qq.com/cgi-bin/get_current_selfmenu_info?access_token=ACCESS_TOKEN
    -   *
    + * http请求方式: GET(请使用https协议) + * https://api.weixin.qq.com/cgi-bin/get_current_selfmenu_info?access_token=ACCESS_TOKEN + * */ WxMpGetSelfMenuInfoResult getSelfMenuInfo() throws WxErrorException; } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMessageMatcher.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMessageMatcher.java index 812992c9..fd522c77 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMessageMatcher.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMessageMatcher.java @@ -9,6 +9,7 @@ public interface WxMpMessageMatcher { /** * 消息是否匹配某种模式 + * * @param message */ boolean match(WxMpXmlMessage message); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMessageRouter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMessageRouter.java index 24dc4451..958c3026 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMessageRouter.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMessageRouter.java @@ -1,15 +1,5 @@ package me.chanjar.weixin.mp.api; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import me.chanjar.weixin.common.api.WxErrorExceptionHandler; import me.chanjar.weixin.common.api.WxMessageDuplicateChecker; import me.chanjar.weixin.common.api.WxMessageInMemoryDuplicateChecker; @@ -20,6 +10,15 @@ import me.chanjar.weixin.common.session.WxSessionManager; import me.chanjar.weixin.common.util.LogExceptionHandler; import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage; import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; /** *
    @@ -46,15 +45,13 @@ import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
      * router.route(message);
      *
      * 
    - * @author Daniel Qian * + * @author Daniel Qian */ public class WxMpMessageRouter { - protected final Logger log = LoggerFactory.getLogger(WxMpMessageRouter.class); - private static final int DEFAULT_THREAD_POOL_SIZE = 100; - + protected final Logger log = LoggerFactory.getLogger(WxMpMessageRouter.class); private final List rules = new ArrayList<>(); private final WxMpService wxMpService; @@ -80,6 +77,7 @@ public class WxMpMessageRouter { * 设置自定义的 {@link ExecutorService} * 如果不调用该方法,默认使用 Executors.newFixedThreadPool(100) * + * * @param executorService */ public void setExecutorService(ExecutorService executorService) { @@ -91,6 +89,7 @@ public class WxMpMessageRouter { * 设置自定义的 {@link me.chanjar.weixin.common.api.WxMessageDuplicateChecker} * 如果不调用该方法,默认使用 {@link me.chanjar.weixin.common.api.WxMessageInMemoryDuplicateChecker} * + * * @param messageDuplicateChecker */ public void setMessageDuplicateChecker(WxMessageDuplicateChecker messageDuplicateChecker) { @@ -102,6 +101,7 @@ public class WxMpMessageRouter { * 设置自定义的{@link me.chanjar.weixin.common.session.WxSessionManager} * 如果不调用该方法,默认使用 {@link me.chanjar.weixin.common.session.StandardSessionManager} * + * * @param sessionManager */ public void setSessionManager(WxSessionManager sessionManager) { @@ -113,6 +113,7 @@ public class WxMpMessageRouter { * 设置自定义的{@link me.chanjar.weixin.common.api.WxErrorExceptionHandler} * 如果不调用该方法,默认使用 {@link me.chanjar.weixin.common.util.LogExceptionHandler} * + * * @param exceptionHandler */ public void setExceptionHandler(WxErrorExceptionHandler exceptionHandler) { @@ -132,6 +133,7 @@ public class WxMpMessageRouter { /** * 处理微信消息 + * * @param wxMessage */ public WxMpXmlOutMessage route(final WxMpXmlMessage wxMessage) { @@ -145,7 +147,7 @@ public class WxMpMessageRouter { for (final WxMpMessageRouterRule rule : this.rules) { if (rule.test(wxMessage)) { matchRules.add(rule); - if(!rule.isReEnter()) { + if (!rule.isReEnter()) { break; } } @@ -159,14 +161,14 @@ public class WxMpMessageRouter { final List> futures = new ArrayList<>(); for (final WxMpMessageRouterRule rule : matchRules) { // 返回最后一个非异步的rule的执行结果 - if(rule.isAsync()) { + if (rule.isAsync()) { futures.add( - this.executorService.submit(new Runnable() { - @Override - public void run() { - rule.service(wxMessage, WxMpMessageRouter.this.wxMpService, WxMpMessageRouter.this.sessionManager, WxMpMessageRouter.this.exceptionHandler); - } - }) + this.executorService.submit(new Runnable() { + @Override + public void run() { + rule.service(wxMessage, WxMpMessageRouter.this.wxMpService, WxMpMessageRouter.this.sessionManager, WxMpMessageRouter.this.exceptionHandler); + } + }) ); } else { res = rule.service(wxMessage, this.wxMpService, this.sessionManager, this.exceptionHandler); @@ -217,11 +219,12 @@ public class WxMpMessageRouter { /** * 对session的访问结束 + * * @param wxMessage */ protected void sessionEndAccess(WxMpXmlMessage wxMessage) { - InternalSession session = ((InternalSessionManager)this.sessionManager).findSession(wxMessage.getFromUser()); + InternalSession session = ((InternalSessionManager) this.sessionManager).findSession(wxMessage.getFromUser()); if (session != null) { session.endAccess(); } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMessageRouterRule.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMessageRouterRule.java index 6859b7d7..eda32b71 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMessageRouterRule.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMessageRouterRule.java @@ -1,8 +1,8 @@ package me.chanjar.weixin.mp.api; +import me.chanjar.weixin.common.api.WxErrorExceptionHandler; import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.common.session.WxSessionManager; -import me.chanjar.weixin.common.api.WxErrorExceptionHandler; import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage; import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage; @@ -168,22 +168,22 @@ public class WxMpMessageRouterRule { */ protected boolean test(WxMpXmlMessage wxMessage) { return - (this.fromUser == null || this.fromUser.equals(wxMessage.getFromUser())) - && - (this.msgType == null || this.msgType.toLowerCase().equals((wxMessage.getMsgType()==null?null:wxMessage.getMsgType().toLowerCase()))) - && - (this.event == null || this.event.toLowerCase().equals((wxMessage.getEvent()==null?null:wxMessage.getEvent().toLowerCase()))) - && - (this.eventKey == null || this.eventKey.toLowerCase().equals((wxMessage.getEventKey()==null?null:wxMessage.getEventKey().toLowerCase()))) - && - (this.content == null || this.content - .equals(wxMessage.getContent() == null ? null : wxMessage.getContent().trim())) - && - (this.rContent == null || Pattern - .matches(this.rContent, wxMessage.getContent() == null ? "" : wxMessage.getContent().trim())) - && - (this.matcher == null || this.matcher.match(wxMessage)) - ; + (this.fromUser == null || this.fromUser.equals(wxMessage.getFromUser())) + && + (this.msgType == null || this.msgType.toLowerCase().equals((wxMessage.getMsgType() == null ? null : wxMessage.getMsgType().toLowerCase()))) + && + (this.event == null || this.event.toLowerCase().equals((wxMessage.getEvent() == null ? null : wxMessage.getEvent().toLowerCase()))) + && + (this.eventKey == null || this.eventKey.toLowerCase().equals((wxMessage.getEventKey() == null ? null : wxMessage.getEventKey().toLowerCase()))) + && + (this.content == null || this.content + .equals(wxMessage.getContent() == null ? null : wxMessage.getContent().trim())) + && + (this.rContent == null || Pattern + .matches(this.rContent, wxMessage.getContent() == null ? "" : wxMessage.getContent().trim())) + && + (this.matcher == null || this.matcher.match(wxMessage)) + ; } /** @@ -193,9 +193,9 @@ public class WxMpMessageRouterRule { * @return true 代表继续执行别的router,false 代表停止执行别的router */ protected WxMpXmlOutMessage service(WxMpXmlMessage wxMessage, - WxMpService wxMpService, - WxSessionManager sessionManager, - WxErrorExceptionHandler exceptionHandler) { + WxMpService wxMpService, + WxSessionManager sessionManager, + WxErrorExceptionHandler exceptionHandler) { try { @@ -211,7 +211,7 @@ public class WxMpMessageRouterRule { WxMpXmlOutMessage res = null; for (WxMpMessageHandler handler : this.handlers) { // 返回最后handler的结果 - if(handler == null){ + if (handler == null) { continue; } res = handler.handle(wxMessage, context, wxMpService, sessionManager); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpQrcodeService.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpQrcodeService.java index ba8665e9..e2e17eb3 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpQrcodeService.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpQrcodeService.java @@ -10,6 +10,7 @@ import java.io.File; * 二维码相关操作接口 * 文档地址:https://mp.weixin.qq.com/wiki?action=doc&id=mp1443433542&t=0.9274944716856435 * + * * @author Binary Wang */ public interface WxMpQrcodeService { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpService.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpService.java index da51c001..33a4066b 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpService.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpService.java @@ -297,11 +297,6 @@ public interface WxMpService { */ //HttpHost getRequestHttpProxy(); - /** - * 注入 {@link WxMpConfigStorage} 的实现 - */ - void setWxMpConfigStorage(WxMpConfigStorage wxConfigProvider); - /** *
        * 设置当微信系统响应系统繁忙时,要等待多少 retrySleepMillis(ms) * 2^(重试次数 - 1) 再发起重试
    @@ -325,6 +320,11 @@ public interface WxMpService {
        */
       WxMpConfigStorage getWxMpConfigStorage();
     
    +  /**
    +   * 注入 {@link WxMpConfigStorage} 的实现
    +   */
    +  void setWxMpConfigStorage(WxMpConfigStorage wxConfigProvider);
    +
       /**
        * 返回客服接口方法实现类,以方便调用其各个接口
        *
    @@ -416,7 +416,6 @@ public interface WxMpService {
       void initHttp();
     
       /**
    -   *
        * @return
        */
       RequestHttp getRequestHttp();
    diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpStoreService.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpStoreService.java
    index 38dde803..2634c3f3 100644
    --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpStoreService.java
    +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpStoreService.java
    @@ -9,10 +9,11 @@ import java.util.List;
     
     /**
      * 门店管理的相关接口代码
    - * @author  binarywang(Binary Wang)
    + *
    + * @author binarywang(Binary Wang)
      *         Created by Binary Wang on 2016-09-23.
      */
    -public interface WxMpStoreService {
    +public interface WxMpStoreService {
       /**
        * 
        * 创建门店
    @@ -23,7 +24,6 @@ public interface WxMpStoreService {
        * 详情请见: 微信门店接口
        * 接口格式: http://api.weixin.qq.com/cgi-bin/poi/addpoi?access_token=TOKEN
        * 
    - * */ void add(WxMpStoreBaseInfo request) throws WxErrorException; @@ -37,7 +37,8 @@ public interface WxMpStoreService { * 详情请见: 微信门店接口 * 接口格式:http://api.weixin.qq.com/cgi-bin/poi/getpoi?access_token=TOKEN *
    - * @param poiId 门店Id + * + * @param poiId 门店Id * @throws WxErrorException */ WxMpStoreBaseInfo get(String poiId) throws WxErrorException; @@ -49,7 +50,8 @@ public interface WxMpStoreService { * 详情请见: 微信门店接口 * 接口格式:http://api.weixin.qq.com/cgi-bin/poi/delpoi?access_token=TOKEN * - * @param poiId 门店Id + * + * @param poiId 门店Id * @throws WxErrorException */ void delete(String poiId) throws WxErrorException; @@ -61,6 +63,7 @@ public interface WxMpStoreService { * 详情请见: 微信门店接口 * 接口格式:http://api.weixin.qq.com/cgi-bin/poi/getpoilist?access_token=TOKEN * + * * @param begin 开始位置,0 即为从第一条开始查询 * @param limit 返回数据条数,最大允许50,默认为20 * @throws WxErrorException @@ -74,6 +77,7 @@ public interface WxMpStoreService { * 详情请见: 微信门店接口 * 接口格式:http://api.weixin.qq.com/cgi-bin/poi/getpoilist?access_token=TOKEN * + * * @throws WxErrorException */ List listAll() throws WxErrorException; @@ -85,6 +89,7 @@ public interface WxMpStoreService { * 详情请见: 微信门店接口 * 接口格式:http://api.weixin.qq.com/cgi-bin/poi/updatepoi?access_token=TOKEN * + * * @throws WxErrorException */ void update(WxMpStoreBaseInfo info) throws WxErrorException; @@ -96,6 +101,7 @@ public interface WxMpStoreService { * 详情请见: 微信门店接口 * 接口格式:http://api.weixin.qq.com/cgi-bin/poi/getwxcategory?access_token=TOKEN * + * * @throws WxErrorException */ List listCategories() throws WxErrorException; diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpTemplateMsgService.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpTemplateMsgService.java index 9b66f722..f9203c16 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpTemplateMsgService.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpTemplateMsgService.java @@ -56,6 +56,7 @@ public interface WxMpTemplateMsgService { * 详情请见: http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433751277&token=&lang=zh_CN * 接口地址格式:https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token=ACCESS_TOKEN * + * * @param shortTemplateId 模板库中模板的编号,有“TM**”和“OPENTMTM**”等形式 * @return templateId 模板Id */ diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpUserService.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpUserService.java index 96499128..e207e5ef 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpUserService.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpUserService.java @@ -48,7 +48,7 @@ public interface WxMpUserService { * * * @param openid 用户openid - * @param lang 语言,zh_CN 简体(默认),zh_TW 繁体,en 英语 + * @param lang 语言,zh_CN 简体(默认),zh_TW 繁体,en 英语 */ WxMpUser userInfo(String openid, String lang) throws WxErrorException; diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpUserTagService.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpUserTagService.java index 4c0ab7c8..cee28b73 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpUserTagService.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpUserTagService.java @@ -1,16 +1,16 @@ package me.chanjar.weixin.mp.api; -import java.util.List; - import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.mp.bean.tag.WxTagListUser; import me.chanjar.weixin.mp.bean.tag.WxUserTag; +import java.util.List; + /** * 用户标签管理相关接口 * Created by Binary Wang on 2016/9/2. - * @author binarywang(Binary Wang) * + * @author binarywang(Binary Wang) */ public interface WxMpUserTagService { @@ -32,7 +32,6 @@ public interface WxMpUserTagService { * 详情请见:用户标签管理 * 接口url格式: https://api.weixin.qq.com/cgi-bin/tags/get?access_token=ACCESS_TOKEN * - * */ List tagGet() throws WxErrorException; @@ -42,7 +41,6 @@ public interface WxMpUserTagService { * 详情请见:用户标签管理 * 接口url格式: https://api.weixin.qq.com/cgi-bin/tags/update?access_token=ACCESS_TOKEN * - * */ Boolean tagUpdate(Long tagId, String name) throws WxErrorException; @@ -52,7 +50,6 @@ public interface WxMpUserTagService { * 详情请见:用户标签管理 * 接口url格式: https://api.weixin.qq.com/cgi-bin/tags/delete?access_token=ACCESS_TOKEN * - * */ Boolean tagDelete(Long tagId) throws WxErrorException; @@ -62,10 +59,9 @@ public interface WxMpUserTagService { * 详情请见:用户标签管理 * 接口url格式: https://api.weixin.qq.com/cgi-bin/user/tag/get?access_token=ACCESS_TOKEN * - * */ WxTagListUser tagListUser(Long tagId, String nextOpenid) - throws WxErrorException; + throws WxErrorException; /** *
    @@ -73,7 +69,6 @@ public interface WxMpUserTagService {
        * 详情请见:用户标签管理
        * 接口url格式: https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token=ACCESS_TOKEN
        * 
    - * */ boolean batchTagging(Long tagId, String[] openids) throws WxErrorException; @@ -83,7 +78,6 @@ public interface WxMpUserTagService { * 详情请见:用户标签管理 * 接口url格式: https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token=ACCESS_TOKEN * - * */ boolean batchUntagging(Long tagId, String[] openids) throws WxErrorException; @@ -94,7 +88,8 @@ public interface WxMpUserTagService { * 详情请见:用户标签管理 * 接口url格式: https://api.weixin.qq.com/cgi-bin/tags/getidlist?access_token=ACCESS_TOKEN * - * @return 标签Id的列表 + * + * @return 标签Id的列表 */ List userTagList(String openid) throws WxErrorException; diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpCardServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpCardServiceImpl.java index ce080330..7bb9b9cc 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpCardServiceImpl.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpCardServiceImpl.java @@ -35,8 +35,8 @@ public class WxMpCardServiceImpl implements WxMpCardService { } @Override - public WxMpService getWxMpService(){ - return this.wxMpService; + public WxMpService getWxMpService() { + return this.wxMpService; } /** @@ -98,13 +98,13 @@ public class WxMpCardServiceImpl implements WxMpCardService { * * * @param optionalSignParam 参与签名的参数数组。 - * 可以为下列字段:app_id, card_id, card_type, code, openid, location_id - *
    注意:当做wx.chooseCard调用时,必须传入app_id参与签名,否则会造成签名失败导致拉取卡券列表为空 + * 可以为下列字段:app_id, card_id, card_type, code, openid, location_id + *
    注意:当做wx.chooseCard调用时,必须传入app_id参与签名,否则会造成签名失败导致拉取卡券列表为空 * @return 卡券Api签名对象 */ @Override public WxCardApiSignature createCardApiSignature(String... optionalSignParam) throws - WxErrorException { + WxErrorException { long timestamp = System.currentTimeMillis() / 1000; String nonceStr = RandomUtils.getRandomStr(); String cardApiTicket = getCardApiTicket(false); @@ -157,8 +157,8 @@ public class WxMpCardServiceImpl implements WxMpCardService { String responseContent = this.wxMpService.post(url, param.toString()); JsonElement tmpJsonElement = new JsonParser().parse(responseContent); return WxMpGsonBuilder.INSTANCE.create().fromJson(tmpJsonElement, - new TypeToken() { - }.getType()); + new TypeToken() { + }.getType()); } /** @@ -206,7 +206,7 @@ public class WxMpCardServiceImpl implements WxMpCardService { */ @Override public void markCardCode(String code, String cardId, String openId, boolean isMark) throws - WxErrorException { + WxErrorException { String url = "https://api.weixin.qq.com/card/code/mark"; JsonObject param = new JsonObject(); param.addProperty("code", code); @@ -216,7 +216,8 @@ public class WxMpCardServiceImpl implements WxMpCardService { String responseContent = this.getWxMpService().post(url, param.toString()); JsonElement tmpJsonElement = new JsonParser().parse(responseContent); WxMpCardResult cardResult = WxMpGsonBuilder.INSTANCE.create().fromJson(tmpJsonElement, - new TypeToken() { }.getType()); + new TypeToken() { + }.getType()); if (!cardResult.getErrorCode().equals("0")) { this.log.warn("朋友的券mark失败:{}", cardResult.getErrorMsg()); } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpDataCubeServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpDataCubeServiceImpl.java index 2dbee076..a1a8d82b 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpDataCubeServiceImpl.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpDataCubeServiceImpl.java @@ -12,7 +12,8 @@ import java.util.Date; import java.util.List; /** - * Created by Binary Wang on 2016/8/23. + * Created by Binary Wang on 2016/8/23. + * * @author binarywang (https://github.com/binarywang) */ public class WxMpDataCubeServiceImpl implements WxMpDataCubeService { @@ -108,7 +109,7 @@ public class WxMpDataCubeServiceImpl implements WxMpDataCubeService { @Override public List getUpstreamMsg(Date beginDate, Date endDate) - throws WxErrorException { + throws WxErrorException { String url = API_URL_PREFIX + "/getupstreammsg"; JsonObject param = new JsonObject(); param.addProperty("begin_date", this.dateFormat.format(beginDate)); @@ -119,7 +120,7 @@ public class WxMpDataCubeServiceImpl implements WxMpDataCubeService { @Override public List getUpstreamMsgHour(Date beginDate, - Date endDate) throws WxErrorException { + Date endDate) throws WxErrorException { String url = API_URL_PREFIX + "/getupstreammsghour"; JsonObject param = new JsonObject(); param.addProperty("begin_date", this.dateFormat.format(beginDate)); @@ -130,7 +131,7 @@ public class WxMpDataCubeServiceImpl implements WxMpDataCubeService { @Override public List getUpstreamMsgWeek(Date beginDate, - Date endDate) throws WxErrorException { + Date endDate) throws WxErrorException { String url = API_URL_PREFIX + "/getupstreammsgweek"; JsonObject param = new JsonObject(); param.addProperty("begin_date", this.dateFormat.format(beginDate)); @@ -141,7 +142,7 @@ public class WxMpDataCubeServiceImpl implements WxMpDataCubeService { @Override public List getUpstreamMsgMonth(Date beginDate, - Date endDate) throws WxErrorException { + Date endDate) throws WxErrorException { String url = API_URL_PREFIX + "/getupstreammsgmonth"; JsonObject param = new JsonObject(); param.addProperty("begin_date", this.dateFormat.format(beginDate)); @@ -152,7 +153,7 @@ public class WxMpDataCubeServiceImpl implements WxMpDataCubeService { @Override public List getUpstreamMsgDist(Date beginDate, - Date endDate) throws WxErrorException { + Date endDate) throws WxErrorException { String url = API_URL_PREFIX + "/getupstreammsgdist"; JsonObject param = new JsonObject(); param.addProperty("begin_date", this.dateFormat.format(beginDate)); @@ -163,7 +164,7 @@ public class WxMpDataCubeServiceImpl implements WxMpDataCubeService { @Override public List getUpstreamMsgDistWeek(Date beginDate, - Date endDate) throws WxErrorException { + Date endDate) throws WxErrorException { String url = API_URL_PREFIX + "/getupstreammsgdistweek"; JsonObject param = new JsonObject(); param.addProperty("begin_date", this.dateFormat.format(beginDate)); @@ -174,7 +175,7 @@ public class WxMpDataCubeServiceImpl implements WxMpDataCubeService { @Override public List getUpstreamMsgDistMonth(Date beginDate, - Date endDate) throws WxErrorException { + Date endDate) throws WxErrorException { String url = API_URL_PREFIX + "/getupstreammsgdistmonth"; JsonObject param = new JsonObject(); param.addProperty("begin_date", this.dateFormat.format(beginDate)); @@ -185,7 +186,7 @@ public class WxMpDataCubeServiceImpl implements WxMpDataCubeService { @Override public List getInterfaceSummary(Date beginDate, - Date endDate) throws WxErrorException { + Date endDate) throws WxErrorException { String url = API_URL_PREFIX + "/getinterfacesummary"; JsonObject param = new JsonObject(); param.addProperty("begin_date", this.dateFormat.format(beginDate)); @@ -196,7 +197,7 @@ public class WxMpDataCubeServiceImpl implements WxMpDataCubeService { @Override public List getInterfaceSummaryHour(Date beginDate, - Date endDate) throws WxErrorException { + Date endDate) throws WxErrorException { String url = API_URL_PREFIX + "/getinterfacesummaryhour"; JsonObject param = new JsonObject(); param.addProperty("begin_date", this.dateFormat.format(beginDate)); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpDeviceServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpDeviceServiceImpl.java index 3f7378e3..284c0a29 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpDeviceServiceImpl.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpDeviceServiceImpl.java @@ -78,8 +78,8 @@ public class WxMpDeviceServiceImpl implements WxMpDeviceService { @Override public WxDeviceBindDeviceResult getBindDevice(String openId) throws WxErrorException { - String url = API_URL_PREFIX+"/get_bind_device"; - String response = this.wxMpService.get(url,"openid="+openId); + String url = API_URL_PREFIX + "/get_bind_device"; + String response = this.wxMpService.get(url, "openid=" + openId); return WxDeviceBindDeviceResult.fromJson(response); } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpMaterialServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpMaterialServiceImpl.java index b24ea80d..bb5857be 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpMaterialServiceImpl.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpMaterialServiceImpl.java @@ -83,7 +83,7 @@ public class WxMpMaterialServiceImpl implements WxMpMaterialService { @Override public InputStream materialImageOrVoiceDownload(String media_id) throws WxErrorException { String url = MATERIAL_API_URL_PREFIX + "/get_material"; - return this.wxMpService.execute(MaterialVoiceAndImageDownloadRequestExecutor.create(this.wxMpService.getRequestHttp(),this.wxMpService.getWxMpConfigStorage().getTmpDirFile()), url, media_id); + return this.wxMpService.execute(MaterialVoiceAndImageDownloadRequestExecutor.create(this.wxMpService.getRequestHttp(), this.wxMpService.getWxMpConfigStorage().getTmpDirFile()), url, media_id); } @Override diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpStoreServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpStoreServiceImpl.java index e1984204..5f1b5f2a 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpStoreServiceImpl.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpStoreServiceImpl.java @@ -16,9 +16,9 @@ import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; import java.util.List; /** - * Created by Binary Wang on 2016/9/26. - * @author binarywang (https://github.com/binarywang) + * Created by Binary Wang on 2016/9/26. * + * @author binarywang (https://github.com/binarywang) */ public class WxMpStoreServiceImpl implements WxMpStoreService { private static final String API_BASE_URL = "http://api.weixin.qq.com/cgi-bin/poi"; @@ -45,21 +45,21 @@ public class WxMpStoreServiceImpl implements WxMpStoreService { public WxMpStoreBaseInfo get(String poiId) throws WxErrorException { String url = API_BASE_URL + "/getpoi"; JsonObject paramObject = new JsonObject(); - paramObject.addProperty("poi_id",poiId); + paramObject.addProperty("poi_id", poiId); String response = this.wxMpService.post(url, paramObject.toString()); WxError wxError = WxError.fromJson(response); if (wxError.getErrorCode() != 0) { throw new WxErrorException(wxError); } return WxMpStoreBaseInfo.fromJson(new JsonParser().parse(response).getAsJsonObject() - .get("business").getAsJsonObject().get("base_info").toString()); + .get("business").getAsJsonObject().get("base_info").toString()); } @Override public void delete(String poiId) throws WxErrorException { String url = API_BASE_URL + "/delpoi"; JsonObject paramObject = new JsonObject(); - paramObject.addProperty("poi_id",poiId); + paramObject.addProperty("poi_id", poiId); String response = this.wxMpService.post(url, paramObject.toString()); WxError wxError = WxError.fromJson(response); if (wxError.getErrorCode() != 0) { @@ -69,7 +69,7 @@ public class WxMpStoreServiceImpl implements WxMpStoreService { @Override public WxMpStoreListResult list(int begin, int limit) - throws WxErrorException { + throws WxErrorException { String url = API_BASE_URL + "/getpoilist"; JsonObject params = new JsonObject(); params.addProperty("begin", begin); @@ -125,8 +125,9 @@ public class WxMpStoreServiceImpl implements WxMpStoreService { } return WxMpGsonBuilder.create().fromJson( - new JsonParser().parse(response).getAsJsonObject().get("category_list"), - new TypeToken>(){}.getType()); + new JsonParser().parse(response).getAsJsonObject().get("category_list"), + new TypeToken>() { + }.getType()); } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpUserServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpUserServiceImpl.java index c796cbd3..ba74f0e4 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpUserServiceImpl.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpUserServiceImpl.java @@ -40,7 +40,7 @@ public class WxMpUserServiceImpl implements WxMpUserService { String url = API_URL_PREFIX + "/info"; lang = lang == null ? "zh_CN" : lang; String responseContent = this.wxMpService.get(url, - "openid=" + openid + "&lang=" + lang); + "openid=" + openid + "&lang=" + lang); return WxMpUser.fromJson(responseContent); } @@ -48,13 +48,13 @@ public class WxMpUserServiceImpl implements WxMpUserService { public WxMpUserList userList(String next_openid) throws WxErrorException { String url = API_URL_PREFIX + "/get"; String responseContent = this.wxMpService.get(url, - next_openid == null ? null : "next_openid=" + next_openid); + next_openid == null ? null : "next_openid=" + next_openid); return WxMpUserList.fromJson(responseContent); } @Override public List userInfoList(List openids) - throws WxErrorException { + throws WxErrorException { return this.userInfoList(new WxMpUserQuery(openids)); } @@ -62,7 +62,7 @@ public class WxMpUserServiceImpl implements WxMpUserService { public List userInfoList(WxMpUserQuery userQuery) throws WxErrorException { String url = API_URL_PREFIX + "/info/batchget"; String responseContent = this.wxMpService.post(url, - userQuery.toJsonString()); + userQuery.toJsonString()); return WxMpUser.fromJsonList(responseContent); } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpUserTagServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpUserTagServiceImpl.java index a1fee937..99f27106 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpUserTagServiceImpl.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpUserTagServiceImpl.java @@ -16,7 +16,6 @@ import org.apache.commons.lang3.StringUtils; import java.util.List; /** - * * @author binarywang(Binary Wang) * Created by Binary Wang on 2016/9/2. */ @@ -88,7 +87,7 @@ public class WxMpUserTagServiceImpl implements WxMpUserTagService { @Override public WxTagListUser tagListUser(Long tagId, String nextOpenid) - throws WxErrorException { + throws WxErrorException { String url = "https://api.weixin.qq.com/cgi-bin/user/tag/get"; JsonObject json = new JsonObject(); @@ -101,7 +100,7 @@ public class WxMpUserTagServiceImpl implements WxMpUserTagService { @Override public boolean batchTagging(Long tagId, String[] openids) - throws WxErrorException { + throws WxErrorException { String url = API_URL_PREFIX + "/members/batchtagging"; JsonObject json = new JsonObject(); @@ -123,7 +122,7 @@ public class WxMpUserTagServiceImpl implements WxMpUserTagService { @Override public boolean batchUntagging(Long tagId, String[] openids) - throws WxErrorException { + throws WxErrorException { String url = API_URL_PREFIX + "/members/batchuntagging"; JsonObject json = new JsonObject(); @@ -153,8 +152,8 @@ public class WxMpUserTagServiceImpl implements WxMpUserTagService { String responseContent = this.wxMpService.post(url, json.toString()); return WxMpGsonBuilder.create().fromJson( - new JsonParser().parse(responseContent).getAsJsonObject().get("tagid_list"), - new TypeToken>() { - }.getType()); + new JsonParser().parse(responseContent).getAsJsonObject().get("tagid_list"), + new TypeToken>() { + }.getType()); } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMassNews.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMassNews.java index 3e65fcde..dc1acd3b 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMassNews.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMassNews.java @@ -36,6 +36,11 @@ public class WxMpMassNews implements Serializable { return this.articles == null || this.articles.isEmpty(); } + @Override + public String toString() { + return ToStringUtils.toSimpleString(this); + } + /** *
        * 群发图文消息article
    @@ -141,9 +146,4 @@ public class WxMpMassNews implements Serializable {
           return ToStringUtils.toSimpleString(this);
         }
       }
    -
    -  @Override
    -  public String toString() {
    -    return ToStringUtils.toSimpleString(this);
    -  }
     }
    diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMassOpenIdsMessage.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMassOpenIdsMessage.java
    index e0b33f0d..73b6c9e2 100644
    --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMassOpenIdsMessage.java
    +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMassOpenIdsMessage.java
    @@ -38,6 +38,7 @@ public class WxMpMassOpenIdsMessage implements Serializable {
        * {@link me.chanjar.weixin.common.api.WxConsts#MASS_MSG_VOICE}
        * 如果msgtype和media_id不匹配的话,会返回系统繁忙的错误
        * 
    + * * @param msgType */ public void setMsgType(String msgType) { @@ -71,28 +72,29 @@ public class WxMpMassOpenIdsMessage implements Serializable { return this.toUsers; } - /** - * 添加openid,最多支持10,000个 - * @param openid - */ - public void addUser(String openid) { - this.toUsers.add(openid); - } - /** * 提供set方法,方便客户端直接设置所有群发对象的openid列表 + * * @param toUsers */ public void setToUsers(List toUsers) { this.toUsers = toUsers; } + /** + * 添加openid,最多支持10,000个 + * + * @param openid + */ + public void addUser(String openid) { + this.toUsers.add(openid); + } + public boolean isSendIgnoreReprint() { return sendIgnoreReprint; } /** - * * @param sendIgnoreReprint 文章被判定为转载时,是否继续进行群发操作。 */ public void setSendIgnoreReprint(boolean sendIgnoreReprint) { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMassTagMessage.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMassTagMessage.java index bf1ded1a..cdf14f79 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMassTagMessage.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMassTagMessage.java @@ -82,7 +82,6 @@ public class WxMpMassTagMessage implements Serializable { } /** - * * @param sendIgnoreReprint 文章被判定为转载时,是否继续进行群发操作。 */ public void setSendIgnoreReprint(boolean sendIgnoreReprint) { @@ -97,7 +96,7 @@ public class WxMpMassTagMessage implements Serializable { } public void setSendAll(boolean sendAll) { - if(sendAll){ + if (sendAll) { this.tagId = null; } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMassVideo.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMassVideo.java index ec94092c..38eef7c8 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMassVideo.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMassVideo.java @@ -6,13 +6,13 @@ import java.io.Serializable; /** * 群发时用到的视频素材 - * + * * @author chanjarster */ public class WxMpMassVideo implements Serializable { /** - * + * */ private static final long serialVersionUID = 9153925016061915637L; private String mediaId; diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpSemanticQuery.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpSemanticQuery.java index c17f38e9..f4b1c3da 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpSemanticQuery.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpSemanticQuery.java @@ -6,7 +6,7 @@ import java.io.Serializable; /** * 语义理解查询用对象 - * + *

    * http://mp.weixin.qq.com/wiki/index.php?title=语义理解 * * @author Daniel Qian @@ -14,7 +14,7 @@ import java.io.Serializable; public class WxMpSemanticQuery implements Serializable { /** - * + * */ private static final long serialVersionUID = 7685873048199870690L; private String query; diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpUserQuery.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpUserQuery.java index e97389b8..800e03e9 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpUserQuery.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpUserQuery.java @@ -1,189 +1,188 @@ -package me.chanjar.weixin.mp.bean; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.google.gson.Gson; - -/** - * 批量查询用户信息查询参数
    - * Created by LiuJunGuang on 2016/8/31. - * - * @author LiuJunGuang - */ -public class WxMpUserQuery { - private List queryParamList = new ArrayList<>(); - - public WxMpUserQuery() { - super(); - } - - /** - * 语言使用默认(zh_CN) - * - * @param openids - */ - public WxMpUserQuery(List openids) { - super(); - add(openids); - } - - /** - * 添加OpenId列表,语言使用默认(zh_CN) - * - * @param openids - * @return {@link WxMpUserQuery} - */ - public WxMpUserQuery add(List openids) { - for (String openid : openids) { - this.add(openid); - } - return this; - } - - /** - * 添加一个OpenId - * - * @param openid - * @param lang 国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语 - * @return {@link WxMpUserQuery} - */ - public WxMpUserQuery add(String openid, String lang) { - this.queryParamList.add(new WxMpUserQueryParam(openid, lang)); - return this; - } - - /** - * 添加一个OpenId到列表中,并返回本对象 - * - *

    -   * 该方法默认lang = zh_CN
    -   * 
    - * - * @param openid - * @return {@link WxMpUserQuery} - */ - public WxMpUserQuery add(String openid) { - this.queryParamList.add(new WxMpUserQueryParam(openid)); - return this; - } - - /** - * 删除指定的OpenId,语言使用默认(zh_CN) - * - * @param openid - * @return {@link WxMpUserQuery} - */ - public WxMpUserQuery remove(String openid) { - this.queryParamList.remove(new WxMpUserQueryParam(openid)); - return this; - } - - /** - * 删除指定的OpenId - * - * @param openid - * @param lang 国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语 - * @return {@link WxMpUserQuery} - */ - public WxMpUserQuery remove(String openid, String lang) { - this.queryParamList.remove(new WxMpUserQueryParam(openid, lang)); - return this; - } - - /** - * 获取查询参数列表 - * - */ - public List getQueryParamList() { - return this.queryParamList; - } - - public String toJsonString() { - Map map = new HashMap<>(); - map.put("user_list", this.queryParamList); - return new Gson().toJson(map); - } - - // 查询参数封装 - public class WxMpUserQueryParam implements Serializable { - private static final long serialVersionUID = -6863571795702385319L; - private String openid; - private String lang; - - public WxMpUserQueryParam(String openid, String lang) { - super(); - this.openid = openid; - this.lang = lang; - } - - public WxMpUserQueryParam(String openid) { - super(); - this.openid = openid; - this.lang = "zh_CN"; - } - - public WxMpUserQueryParam() { - super(); - } - - public String getOpenid() { - return this.openid; - } - - public void setOpenid(String openid) { - this.openid = openid; - } - - public String getLang() { - return this.lang; - } - - public void setLang(String lang) { - this.lang = lang; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + getOuterType().hashCode(); - result = prime * result + ((this.lang == null) ? 0 : this.lang.hashCode()); - result = prime * result + ((this.openid == null) ? 0 : this.openid.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - WxMpUserQueryParam other = (WxMpUserQueryParam) obj; - if (!getOuterType().equals(other.getOuterType())) - return false; - if (this.lang == null) { - if (other.lang != null) - return false; - } else if (!this.lang.equals(other.lang)) - return false; - if (this.openid == null) { - if (other.openid != null) - return false; - } else if (!this.openid.equals(other.openid)) - return false; - return true; - } - - private WxMpUserQuery getOuterType() { - return WxMpUserQuery.this; - } - - } - -} +package me.chanjar.weixin.mp.bean; + +import com.google.gson.Gson; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 批量查询用户信息查询参数
    + * Created by LiuJunGuang on 2016/8/31. + * + * @author LiuJunGuang + */ +public class WxMpUserQuery { + private List queryParamList = new ArrayList<>(); + + public WxMpUserQuery() { + super(); + } + + /** + * 语言使用默认(zh_CN) + * + * @param openids + */ + public WxMpUserQuery(List openids) { + super(); + add(openids); + } + + /** + * 添加OpenId列表,语言使用默认(zh_CN) + * + * @param openids + * @return {@link WxMpUserQuery} + */ + public WxMpUserQuery add(List openids) { + for (String openid : openids) { + this.add(openid); + } + return this; + } + + /** + * 添加一个OpenId + * + * @param openid + * @param lang 国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语 + * @return {@link WxMpUserQuery} + */ + public WxMpUserQuery add(String openid, String lang) { + this.queryParamList.add(new WxMpUserQueryParam(openid, lang)); + return this; + } + + /** + * 添加一个OpenId到列表中,并返回本对象 + *

    + *

    +   * 该方法默认lang = zh_CN
    +   * 
    + * + * @param openid + * @return {@link WxMpUserQuery} + */ + public WxMpUserQuery add(String openid) { + this.queryParamList.add(new WxMpUserQueryParam(openid)); + return this; + } + + /** + * 删除指定的OpenId,语言使用默认(zh_CN) + * + * @param openid + * @return {@link WxMpUserQuery} + */ + public WxMpUserQuery remove(String openid) { + this.queryParamList.remove(new WxMpUserQueryParam(openid)); + return this; + } + + /** + * 删除指定的OpenId + * + * @param openid + * @param lang 国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语 + * @return {@link WxMpUserQuery} + */ + public WxMpUserQuery remove(String openid, String lang) { + this.queryParamList.remove(new WxMpUserQueryParam(openid, lang)); + return this; + } + + /** + * 获取查询参数列表 + */ + public List getQueryParamList() { + return this.queryParamList; + } + + public String toJsonString() { + Map map = new HashMap<>(); + map.put("user_list", this.queryParamList); + return new Gson().toJson(map); + } + + // 查询参数封装 + public class WxMpUserQueryParam implements Serializable { + private static final long serialVersionUID = -6863571795702385319L; + private String openid; + private String lang; + + public WxMpUserQueryParam(String openid, String lang) { + super(); + this.openid = openid; + this.lang = lang; + } + + public WxMpUserQueryParam(String openid) { + super(); + this.openid = openid; + this.lang = "zh_CN"; + } + + public WxMpUserQueryParam() { + super(); + } + + public String getOpenid() { + return this.openid; + } + + public void setOpenid(String openid) { + this.openid = openid; + } + + public String getLang() { + return this.lang; + } + + public void setLang(String lang) { + this.lang = lang; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + getOuterType().hashCode(); + result = prime * result + ((this.lang == null) ? 0 : this.lang.hashCode()); + result = prime * result + ((this.openid == null) ? 0 : this.openid.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + WxMpUserQueryParam other = (WxMpUserQueryParam) obj; + if (!getOuterType().equals(other.getOuterType())) + return false; + if (this.lang == null) { + if (other.lang != null) + return false; + } else if (!this.lang.equals(other.lang)) + return false; + if (this.openid == null) { + if (other.openid != null) + return false; + } else if (!this.openid.equals(other.openid)) + return false; + return true; + } + + private WxMpUserQuery getOuterType() { + return WxMpUserQuery.this; + } + + } + +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeArticleResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeArticleResult.java index 35cae74d..fe6627d2 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeArticleResult.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeArticleResult.java @@ -9,6 +9,7 @@ import java.util.List; /** * 图文分析数据接口返回结果对象 + * * @author binarywang(Binary Wang) * Created by Binary Wang on 2016/8/24. */ @@ -109,6 +110,13 @@ public class WxDataCubeArticleResult extends WxDataCubeBaseResult { @SerializedName("user_source") private Integer userSource; + public static List fromJson(String json) { + return WxMpGsonBuilder.INSTANCE.create().fromJson( + JSON_PARSER.parse(json).getAsJsonObject().get("list"), + new TypeToken>() { + }.getType()); + } + public Integer getRefHour() { return this.refHour; } @@ -212,11 +220,4 @@ public class WxDataCubeArticleResult extends WxDataCubeBaseResult { public void setUserSource(Integer userSource) { this.userSource = userSource; } - - public static List fromJson(String json) { - return WxMpGsonBuilder.INSTANCE.create().fromJson( - JSON_PARSER.parse(json).getAsJsonObject().get("list"), - new TypeToken>() { - }.getType()); - } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeArticleTotal.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeArticleTotal.java index d3236be3..eee6240f 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeArticleTotal.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeArticleTotal.java @@ -1,15 +1,15 @@ package me.chanjar.weixin.mp.bean.datacube; -import java.util.List; - import com.google.gson.JsonParser; import com.google.gson.annotations.SerializedName; import com.google.gson.reflect.TypeToken; - import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; +import java.util.List; + /** * 图文分析数据接口返回结果对象 + * * @author binarywang(Binary Wang) * Created by Binary Wang on 2016/8/24. */ @@ -38,6 +38,13 @@ public class WxDataCubeArticleTotal extends WxDataCubeBaseResult { @SerializedName("details") private List details; + public static List fromJson(String json) { + return WxMpGsonBuilder.INSTANCE.create().fromJson( + JSON_PARSER.parse(json).getAsJsonObject().get("list"), + new TypeToken>() { + }.getType()); + } + public String getMsgId() { return this.msgId; } @@ -61,11 +68,4 @@ public class WxDataCubeArticleTotal extends WxDataCubeBaseResult { public void setDetails(List details) { this.details = details; } - - public static List fromJson(String json) { - return WxMpGsonBuilder.INSTANCE.create().fromJson( - JSON_PARSER.parse(json).getAsJsonObject().get("list"), - new TypeToken>() { - }.getType()); - } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeArticleTotalDetail.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeArticleTotalDetail.java index 251c5e76..27f9b8aa 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeArticleTotalDetail.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeArticleTotalDetail.java @@ -4,6 +4,7 @@ import com.google.gson.annotations.SerializedName; /** * 获取图文群发总数据接口(getarticletotal)中的详细字段 + * * @author binarywang(Binary Wang) * Created by Binary Wang on 2016/8/24. */ @@ -80,114 +81,114 @@ public class WxDataCubeArticleTotalDetail { private Integer addToFavCount; /** - * int_page_from_session_read_user - * 公众号会话阅读人数 - */ + * int_page_from_session_read_user + * 公众号会话阅读人数 + */ @SerializedName("int_page_from_session_read_user") private Integer intPageFromSessionReadUser; /** - * int_page_from_session_read_count - * 公众号会话阅读次数 - */ + * int_page_from_session_read_count + * 公众号会话阅读次数 + */ @SerializedName("int_page_from_session_read_count") private Integer intPageFromSessionReadCount; /** - * int_page_from_hist_msg_read_user - * 历史消息页阅读人数 - */ + * int_page_from_hist_msg_read_user + * 历史消息页阅读人数 + */ @SerializedName("int_page_from_hist_msg_read_user") private Integer intPageFromHistMsgReadUser; /** - * int_page_from_hist_msg_read_count - * 历史消息页阅读次数 - */ + * int_page_from_hist_msg_read_count + * 历史消息页阅读次数 + */ @SerializedName("int_page_from_hist_msg_read_count") private Integer intPageFromHistMsgReadCount; /** - * int_page_from_feed_read_user - * 朋友圈阅读人数 - */ + * int_page_from_feed_read_user + * 朋友圈阅读人数 + */ @SerializedName("int_page_from_feed_read_user") private Integer intPageFromFeedReadUser; /** - * int_page_from_feed_read_count - * 朋友圈阅读次数 - */ + * int_page_from_feed_read_count + * 朋友圈阅读次数 + */ @SerializedName("int_page_from_feed_read_count") private Integer intPageFromFeedReadCount; /** - * int_page_from_friends_read_user - * 好友转发阅读人数 - */ + * int_page_from_friends_read_user + * 好友转发阅读人数 + */ @SerializedName("int_page_from_friends_read_user") private Integer intPageFromFriendsReadUser; /** - * int_page_from_friends_read_count - * 好友转发阅读次数 - */ + * int_page_from_friends_read_count + * 好友转发阅读次数 + */ @SerializedName("int_page_from_friends_read_count") private Integer intPageFromFriendsReadCount; /** - * int_page_from_other_read_user - * 其他场景阅读人数 - */ + * int_page_from_other_read_user + * 其他场景阅读人数 + */ @SerializedName("int_page_from_other_read_user") private Integer intPageFromOtherReadUser; /** - * int_page_from_other_read_count - * 其他场景阅读次数 - */ + * int_page_from_other_read_count + * 其他场景阅读次数 + */ @SerializedName("int_page_from_other_read_count") private Integer intPageFromOtherReadCount; /** - * feed_share_from_session_user - * 公众号会话转发朋友圈人数 - */ + * feed_share_from_session_user + * 公众号会话转发朋友圈人数 + */ @SerializedName("feed_share_from_session_user") private Integer feedShareFromSessionUser; /** - * feed_share_from_session_cnt - * 公众号会话转发朋友圈次数 - */ + * feed_share_from_session_cnt + * 公众号会话转发朋友圈次数 + */ @SerializedName("feed_share_from_session_cnt") private Integer feedShareFromSessionCnt; /** - * feed_share_from_feed_user - * 朋友圈转发朋友圈人数 - */ + * feed_share_from_feed_user + * 朋友圈转发朋友圈人数 + */ @SerializedName("feed_share_from_feed_user") private Integer feedShareFromFeedUser; /** - * feed_share_from_feed_cnt - * 朋友圈转发朋友圈次数 - */ + * feed_share_from_feed_cnt + * 朋友圈转发朋友圈次数 + */ @SerializedName("feed_share_from_feed_cnt") private Integer feedShareFromFeedCnt; /** - * feed_share_from_other_user - * 其他场景转发朋友圈人数 - */ + * feed_share_from_other_user + * 其他场景转发朋友圈人数 + */ @SerializedName("feed_share_from_other_user") private Integer feedShareFromOtherUser; /** - * feed_share_from_other_cnt - * 其他场景转发朋友圈次数 - */ + * feed_share_from_other_cnt + * 其他场景转发朋友圈次数 + */ @SerializedName("feed_share_from_other_cnt") private Integer feedShareFromOtherCnt; @@ -284,7 +285,7 @@ public class WxDataCubeArticleTotalDetail { } public void setIntPageFromSessionReadCount( - Integer intPageFromSessionReadCount) { + Integer intPageFromSessionReadCount) { this.intPageFromSessionReadCount = intPageFromSessionReadCount; } @@ -301,7 +302,7 @@ public class WxDataCubeArticleTotalDetail { } public void setIntPageFromHistMsgReadCount( - Integer intPageFromHistMsgReadCount) { + Integer intPageFromHistMsgReadCount) { this.intPageFromHistMsgReadCount = intPageFromHistMsgReadCount; } @@ -334,7 +335,7 @@ public class WxDataCubeArticleTotalDetail { } public void setIntPageFromFriendsReadCount( - Integer intPageFromFriendsReadCount) { + Integer intPageFromFriendsReadCount) { this.intPageFromFriendsReadCount = intPageFromFriendsReadCount; } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeBaseResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeBaseResult.java index a9415d9f..25fbcc62 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeBaseResult.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeBaseResult.java @@ -5,15 +5,11 @@ import me.chanjar.weixin.common.util.ToStringUtils; /** * 统计接口的共用属性类 + * * @author binarywang(Binary Wang) * Created by Binary Wang on 2016/8/25. */ public class WxDataCubeBaseResult { - @Override - public String toString() { - return ToStringUtils.toSimpleString(this); - } - /** * ref_date * 数据的日期,需在begin_date和end_date之间 @@ -21,6 +17,11 @@ public class WxDataCubeBaseResult { @SerializedName("ref_date") private String refDate; + @Override + public String toString() { + return ToStringUtils.toSimpleString(this); + } + public String getRefDate() { return this.refDate; } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeInterfaceResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeInterfaceResult.java index 2088453c..9606c6f9 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeInterfaceResult.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeInterfaceResult.java @@ -1,15 +1,15 @@ package me.chanjar.weixin.mp.bean.datacube; -import java.util.List; - import com.google.gson.JsonParser; import com.google.gson.annotations.SerializedName; import com.google.gson.reflect.TypeToken; - import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; +import java.util.List; + /** * 接口分析数据接口返回结果对象 + * * @author binarywang(Binary Wang) * Created by Binary Wang on 2016/8/30. */ @@ -52,6 +52,13 @@ public class WxDataCubeInterfaceResult extends WxDataCubeBaseResult { @SerializedName("max_time_cost") private Integer maxTimeCost; + public static List fromJson(String json) { + return WxMpGsonBuilder.INSTANCE.create().fromJson( + JSON_PARSER.parse(json).getAsJsonObject().get("list"), + new TypeToken>() { + }.getType()); + } + public Integer getRefHour() { return this.refHour; } @@ -92,11 +99,4 @@ public class WxDataCubeInterfaceResult extends WxDataCubeBaseResult { this.maxTimeCost = maxTimeCost; } - public static List fromJson(String json) { - return WxMpGsonBuilder.INSTANCE.create().fromJson( - JSON_PARSER.parse(json).getAsJsonObject().get("list"), - new TypeToken>() { - }.getType()); - } - } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeMsgResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeMsgResult.java index 01e40e80..b3592190 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeMsgResult.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeMsgResult.java @@ -1,15 +1,15 @@ package me.chanjar.weixin.mp.bean.datacube; -import java.util.List; - import com.google.gson.JsonParser; import com.google.gson.annotations.SerializedName; import com.google.gson.reflect.TypeToken; - import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; +import java.util.List; + /** * 消息分析数据接口返回结果对象 + * * @author binarywang(Binary Wang) * Created by Binary Wang on 2016/8/29. */ @@ -66,6 +66,13 @@ public class WxDataCubeMsgResult extends WxDataCubeBaseResult { @SerializedName("ori_page_read_user") private Integer oriPageReadUser; + public static List fromJson(String json) { + return WxMpGsonBuilder.INSTANCE.create().fromJson( + JSON_PARSER.parse(json).getAsJsonObject().get("list"), + new TypeToken>() { + }.getType()); + } + public Integer getRefHour() { return this.refHour; } @@ -122,11 +129,4 @@ public class WxDataCubeMsgResult extends WxDataCubeBaseResult { this.oriPageReadUser = oriPageReadUser; } - public static List fromJson(String json) { - return WxMpGsonBuilder.INSTANCE.create().fromJson( - JSON_PARSER.parse(json).getAsJsonObject().get("list"), - new TypeToken>() { - }.getType()); - } - } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeUserCumulate.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeUserCumulate.java index 40e35ded..32f8d5f5 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeUserCumulate.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeUserCumulate.java @@ -25,6 +25,13 @@ public class WxDataCubeUserCumulate implements Serializable { private Integer cumulateUser; + public static List fromJson(String json) { + return WxMpGsonBuilder.INSTANCE.create().fromJson( + JSON_PARSER.parse(json).getAsJsonObject().get("list"), + new TypeToken>() { + }.getType()); + } + public Date getRefDate() { return this.refDate; } @@ -45,11 +52,4 @@ public class WxDataCubeUserCumulate implements Serializable { public String toString() { return ToStringUtils.toSimpleString(this); } - - public static List fromJson(String json) { - return WxMpGsonBuilder.INSTANCE.create().fromJson( - JSON_PARSER.parse(json).getAsJsonObject().get("list"), - new TypeToken>() { - }.getType()); - } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeUserSummary.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeUserSummary.java index 8f478885..3b76725c 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeUserSummary.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeUserSummary.java @@ -28,6 +28,13 @@ public class WxDataCubeUserSummary implements Serializable { private Integer cancelUser; + public static List fromJson(String json) { + return WxMpGsonBuilder.INSTANCE.create().fromJson( + JSON_PARSER.parse(json).getAsJsonObject().get("list"), + new TypeToken>() { + }.getType()); + } + public Date getRefDate() { return this.refDate; } @@ -64,11 +71,4 @@ public class WxDataCubeUserSummary implements Serializable { public String toString() { return ToStringUtils.toSimpleString(this); } - - public static List fromJson(String json) { - return WxMpGsonBuilder.INSTANCE.create().fromJson( - JSON_PARSER.parse(json).getAsJsonObject().get("list"), - new TypeToken>() { - }.getType()); - } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/device/BaseResp.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/device/BaseResp.java index b0dd6ec3..4b6e52d8 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/device/BaseResp.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/device/BaseResp.java @@ -5,7 +5,7 @@ import com.google.gson.annotations.SerializedName; /** * Created by keungtung on 10/12/2016. */ -public class BaseResp extends AbstractDeviceBean{ +public class BaseResp extends AbstractDeviceBean { @SerializedName("base_info") private BaseInfo baseInfo; @SerializedName("errcode") diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/device/RespMsg.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/device/RespMsg.java index f1fdedff..1932e1d1 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/device/RespMsg.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/device/RespMsg.java @@ -6,7 +6,7 @@ import com.google.gson.annotations.SerializedName; * Created by keungtung on 10/12/2016. */ -public class RespMsg extends AbstractDeviceBean{ +public class RespMsg extends AbstractDeviceBean { @SerializedName("ret_code") private Integer retCode; @SerializedName("error_info") diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/device/TransMsgResp.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/device/TransMsgResp.java index 8828b25c..31525f6b 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/device/TransMsgResp.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/device/TransMsgResp.java @@ -6,7 +6,7 @@ import me.chanjar.weixin.common.util.json.WxGsonBuilder; /** * Created by keungtung on 14/12/2016. */ -public class TransMsgResp extends AbstractDeviceBean{ +public class TransMsgResp extends AbstractDeviceBean { private Integer ret; @SerializedName("ret_info") private String retInfo; diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/device/WxDeviceAuthorizeResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/device/WxDeviceAuthorizeResult.java index dfe8d3b7..83ea27c5 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/device/WxDeviceAuthorizeResult.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/device/WxDeviceAuthorizeResult.java @@ -7,7 +7,7 @@ import java.util.List; /** * Created by keungtung on 10/12/2016. */ -public class WxDeviceAuthorizeResult extends AbstractDeviceBean{ +public class WxDeviceAuthorizeResult extends AbstractDeviceBean { private List resp; public static WxDeviceAuthorizeResult fromJson(String response) { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/device/WxDeviceBind.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/device/WxDeviceBind.java index 467f3c42..1acf5962 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/device/WxDeviceBind.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/device/WxDeviceBind.java @@ -5,7 +5,7 @@ import com.google.gson.annotations.SerializedName; /** * Created by keungtung on 10/12/2016. */ -public class WxDeviceBind extends AbstractDeviceBean{ +public class WxDeviceBind extends AbstractDeviceBean { private String ticket; @SerializedName("device_id") private String deviceId; diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/device/WxDeviceBindResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/device/WxDeviceBindResult.java index 26bdb84c..2cbf0078 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/device/WxDeviceBindResult.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/device/WxDeviceBindResult.java @@ -6,7 +6,7 @@ import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; /** * Created by keungtung on 10/12/2016. */ -public class WxDeviceBindResult extends AbstractDeviceBean{ +public class WxDeviceBindResult extends AbstractDeviceBean { @SerializedName("base_resp") private BaseResp baseResp; diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/device/WxDeviceMsg.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/device/WxDeviceMsg.java index bed1a8a2..680209fd 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/device/WxDeviceMsg.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/device/WxDeviceMsg.java @@ -6,7 +6,7 @@ import me.chanjar.weixin.common.util.ToStringUtils; /** * Created by keungtung on 10/12/2016. */ -public class WxDeviceMsg extends AbstractDeviceBean{ +public class WxDeviceMsg extends AbstractDeviceBean { @SerializedName("device_type") private String deviceType; @SerializedName("device_id") diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/WxMpKefuMessage.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/WxMpKefuMessage.java index 228351fd..2c02a620 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/WxMpKefuMessage.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/WxMpKefuMessage.java @@ -1,19 +1,12 @@ package me.chanjar.weixin.mp.bean.kefu; +import me.chanjar.weixin.mp.builder.kefu.*; +import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; + import java.io.Serializable; import java.util.ArrayList; import java.util.List; -import me.chanjar.weixin.mp.builder.kefu.ImageBuilder; -import me.chanjar.weixin.mp.builder.kefu.MpNewsBuilder; -import me.chanjar.weixin.mp.builder.kefu.MusicBuilder; -import me.chanjar.weixin.mp.builder.kefu.NewsBuilder; -import me.chanjar.weixin.mp.builder.kefu.TextBuilder; -import me.chanjar.weixin.mp.builder.kefu.VideoBuilder; -import me.chanjar.weixin.mp.builder.kefu.VoiceBuilder; -import me.chanjar.weixin.mp.builder.kefu.WxCardBuilder; -import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; - /** * 客服消息 * @@ -104,14 +97,6 @@ public class WxMpKefuMessage implements Serializable { return this.msgType; } - public String getMpNewsMediaId() { - return this.mpNewsMediaId; - } - - public void setMpNewsMediaId(String mpNewsMediaId) { - this.mpNewsMediaId = mpNewsMediaId; - } - /** *
        * 请使用
    @@ -131,6 +116,14 @@ public class WxMpKefuMessage implements Serializable {
         this.msgType = msgType;
       }
     
    +  public String getMpNewsMediaId() {
    +    return this.mpNewsMediaId;
    +  }
    +
    +  public void setMpNewsMediaId(String mpNewsMediaId) {
    +    this.mpNewsMediaId = mpNewsMediaId;
    +  }
    +
       public String getContent() {
         return this.content;
       }
    diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfInfo.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfInfo.java
    index 868bf519..c879e9f6 100644
    --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfInfo.java
    +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfInfo.java
    @@ -8,8 +8,8 @@ import java.io.Serializable;
     
     /**
      * 客服基本信息以及客服在线状态信息
    - * @author Binary Wang
      *
    + * @author Binary Wang
      */
     public class WxMpKfInfo implements Serializable {
       private static final long serialVersionUID = -5877300750666022290L;
    @@ -63,7 +63,7 @@ public class WxMpKfInfo implements Serializable {
       private String inviteStatus;
     
       /**
    -   *  status 客服在线状态,目前为:1、web 在线
    +   * status 客服在线状态,目前为:1、web 在线
        */
       @SerializedName("status")
       private Integer status;
    diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfList.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfList.java
    index 9ec9eeff..b5cef947 100644
    --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfList.java
    +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfList.java
    @@ -5,15 +5,18 @@ import me.chanjar.weixin.common.util.ToStringUtils;
     import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;
     
     import java.util.List;
    +
     /**
    - *
      * @author Binary Wang
    - *
      */
     public class WxMpKfList {
       @SerializedName("kf_list")
       private List kfList;
     
    +  public static WxMpKfList fromJson(String json) {
    +    return WxMpGsonBuilder.INSTANCE.create().fromJson(json, WxMpKfList.class);
    +  }
    +
       @Override
       public String toString() {
         return ToStringUtils.toSimpleString(this);
    @@ -26,8 +29,4 @@ public class WxMpKfList {
       public void setKfList(List kfList) {
         this.kfList = kfList;
       }
    -
    -  public static WxMpKfList fromJson(String json) {
    -    return WxMpGsonBuilder.INSTANCE.create().fromJson(json, WxMpKfList.class);
    -  }
     }
    diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfMsgList.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfMsgList.java
    index 7c04acb3..02d24919 100644
    --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfMsgList.java
    +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfMsgList.java
    @@ -19,6 +19,10 @@ public class WxMpKfMsgList {
       @SerializedName("msgid")
       private Long msgId;
     
    +  public static WxMpKfMsgList fromJson(String responseContent) {
    +    return WxMpGsonBuilder.INSTANCE.create().fromJson(responseContent, WxMpKfMsgList.class);
    +  }
    +
       public List getRecords() {
         return this.records;
       }
    @@ -47,8 +51,4 @@ public class WxMpKfMsgList {
       public String toString() {
         return ToStringUtils.toSimpleString(this);
       }
    -
    -  public static WxMpKfMsgList fromJson(String responseContent) {
    -    return WxMpGsonBuilder.INSTANCE.create().fromJson(responseContent, WxMpKfMsgList.class);
    -  }
     }
    diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfMsgRecord.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfMsgRecord.java
    index 0ed9c0b2..c7ada500 100644
    --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfMsgRecord.java
    +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfMsgRecord.java
    @@ -31,7 +31,7 @@ public class WxMpKfMsgRecord {
       @SerializedName("text")
       private String text;
     
    -   /**
    +  /**
        * time	操作时间,unix时间戳
        */
       @SerializedName("time")
    diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfOnlineList.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfOnlineList.java
    index 97500095..1f7545cb 100644
    --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfOnlineList.java
    +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfOnlineList.java
    @@ -5,15 +5,18 @@ import me.chanjar.weixin.common.util.ToStringUtils;
     import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;
     
     import java.util.List;
    +
     /**
    - *
      * @author Binary Wang
    - *
      */
     public class WxMpKfOnlineList {
       @SerializedName("kf_online_list")
       private List kfOnlineList;
     
    +  public static WxMpKfOnlineList fromJson(String json) {
    +    return WxMpGsonBuilder.INSTANCE.create().fromJson(json, WxMpKfOnlineList.class);
    +  }
    +
       @Override
       public String toString() {
         return ToStringUtils.toSimpleString(this);
    @@ -26,8 +29,4 @@ public class WxMpKfOnlineList {
       public void setKfOnlineList(List kfOnlineList) {
         this.kfOnlineList = kfOnlineList;
       }
    -
    -  public static WxMpKfOnlineList fromJson(String json) {
    -    return WxMpGsonBuilder.INSTANCE.create().fromJson(json, WxMpKfOnlineList.class);
    -  }
     }
    diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfSession.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfSession.java
    index da29b4ae..500fc757 100644
    --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfSession.java
    +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfSession.java
    @@ -4,9 +4,7 @@ import com.google.gson.annotations.SerializedName;
     import me.chanjar.weixin.common.util.ToStringUtils;
     
     /**
    - *
      * @author Binary Wang
    - *
      */
     public class WxMpKfSession {
       /**
    diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfSessionGetResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfSessionGetResult.java
    index 2eb73143..b0177acd 100644
    --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfSessionGetResult.java
    +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfSessionGetResult.java
    @@ -5,9 +5,7 @@ import me.chanjar.weixin.common.util.ToStringUtils;
     import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;
     
     /**
    - *
      * @author Binary Wang
    - *
      */
     public class WxMpKfSessionGetResult {
       /**
    @@ -22,15 +20,15 @@ public class WxMpKfSessionGetResult {
       @SerializedName("createtime")
       private long createTime;
     
    +  public static WxMpKfSessionGetResult fromJson(String json) {
    +    return WxMpGsonBuilder.INSTANCE.create().fromJson(json, WxMpKfSessionGetResult.class);
    +  }
    +
       @Override
       public String toString() {
         return ToStringUtils.toSimpleString(this);
       }
     
    -  public static WxMpKfSessionGetResult fromJson(String json) {
    -    return WxMpGsonBuilder.INSTANCE.create().fromJson(json, WxMpKfSessionGetResult.class);
    -  }
    -
       public String getKfAccount() {
         return this.kfAccount;
       }
    diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfSessionList.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfSessionList.java
    index a9a0640e..dd036686 100644
    --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfSessionList.java
    +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfSessionList.java
    @@ -7,9 +7,7 @@ import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;
     import java.util.List;
     
     /**
    - *
      * @author Binary Wang
    - *
      */
     public class WxMpKfSessionList {
       /**
    @@ -18,16 +16,16 @@ public class WxMpKfSessionList {
       @SerializedName("sessionlist")
       private List kfSessionList;
     
    +  public static WxMpKfSessionList fromJson(String json) {
    +    return WxMpGsonBuilder.INSTANCE.create().fromJson(json,
    +      WxMpKfSessionList.class);
    +  }
    +
       @Override
       public String toString() {
         return ToStringUtils.toSimpleString(this);
       }
     
    -  public static WxMpKfSessionList fromJson(String json) {
    -    return WxMpGsonBuilder.INSTANCE.create().fromJson(json,
    -        WxMpKfSessionList.class);
    -  }
    -
       public List getKfSessionList() {
         return this.kfSessionList;
       }
    diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfSessionWaitCaseList.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfSessionWaitCaseList.java
    index 22bcc4da..562113f1 100644
    --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfSessionWaitCaseList.java
    +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfSessionWaitCaseList.java
    @@ -7,9 +7,7 @@ import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;
     import java.util.List;
     
     /**
    - *
      * @author Binary Wang
    - *
      */
     public class WxMpKfSessionWaitCaseList {
       /**
    @@ -24,16 +22,16 @@ public class WxMpKfSessionWaitCaseList {
       @SerializedName("waitcaselist")
       private List kfSessionWaitCaseList;
     
    +  public static WxMpKfSessionWaitCaseList fromJson(String json) {
    +    return WxMpGsonBuilder.INSTANCE.create().fromJson(json,
    +      WxMpKfSessionWaitCaseList.class);
    +  }
    +
       @Override
       public String toString() {
         return ToStringUtils.toSimpleString(this);
       }
     
    -  public static WxMpKfSessionWaitCaseList fromJson(String json) {
    -    return WxMpGsonBuilder.INSTANCE.create().fromJson(json,
    -        WxMpKfSessionWaitCaseList.class);
    -  }
    -
       public List getKfSessionWaitCaseList() {
         return this.kfSessionWaitCaseList;
       }
    diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/material/WxMpMaterialNews.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/material/WxMpMaterialNews.java
    index f67a8cb4..a107faca 100644
    --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/material/WxMpMaterialNews.java
    +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/material/WxMpMaterialNews.java
    @@ -28,6 +28,11 @@ public class WxMpMaterialNews implements Serializable {
         return this.articles == null || this.articles.isEmpty();
       }
     
    +  @Override
    +  public String toString() {
    +    return ToStringUtils.toSimpleString(this);
    +  }
    +
       /**
        * 
        * 群发图文消息article
    @@ -79,7 +84,7 @@ public class WxMpMaterialNews implements Serializable {
     
         /**
          * 点击图文消息跳转链接
    -    */
    +     */
         private String url;
     
         public String getThumbMediaId() {
    @@ -139,11 +144,11 @@ public class WxMpMaterialNews implements Serializable {
         }
     
         public String getUrl() {
    -        return this.url;
    +      return this.url;
         }
     
         public void setUrl(String url) {
    -        this.url = url;
    +      this.url = url;
         }
     
         public String getThumbUrl() {
    @@ -159,9 +164,4 @@ public class WxMpMaterialNews implements Serializable {
           return ToStringUtils.toSimpleString(this);
         }
       }
    -
    -  @Override
    -  public String toString() {
    -    return ToStringUtils.toSimpleString(this);
    -  }
     }
    diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/material/WxMpMaterialUploadResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/material/WxMpMaterialUploadResult.java
    index 2b3a1e57..ec1d1154 100644
    --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/material/WxMpMaterialUploadResult.java
    +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/material/WxMpMaterialUploadResult.java
    @@ -13,6 +13,10 @@ public class WxMpMaterialUploadResult implements Serializable {
       private String mediaId;
       private String url;
     
    +  public static WxMpMaterialUploadResult fromJson(String json) {
    +    return WxMpGsonBuilder.create().fromJson(json, WxMpMaterialUploadResult.class);
    +  }
    +
       public String getMediaId() {
         return this.mediaId;
       }
    @@ -29,10 +33,6 @@ public class WxMpMaterialUploadResult implements Serializable {
         this.url = url;
       }
     
    -  public static WxMpMaterialUploadResult fromJson(String json) {
    -    return WxMpGsonBuilder.create().fromJson(json, WxMpMaterialUploadResult.class);
    -  }
    -
       @Override
       public String toString() {
         return "WxMpMaterialUploadResult [media_id=" + this.mediaId + ", url=" + this.url + "]";
    diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/material/WxMpMaterialVideoInfoResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/material/WxMpMaterialVideoInfoResult.java
    index 06b85b7e..be5dd3f8 100644
    --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/material/WxMpMaterialVideoInfoResult.java
    +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/material/WxMpMaterialVideoInfoResult.java
    @@ -14,6 +14,10 @@ public class WxMpMaterialVideoInfoResult implements Serializable {
       private String description;
       private String downUrl;
     
    +  public static WxMpMaterialVideoInfoResult fromJson(String json) {
    +    return WxMpGsonBuilder.create().fromJson(json, WxMpMaterialVideoInfoResult.class);
    +  }
    +
       public String getTitle() {
         return this.title;
       }
    @@ -38,10 +42,6 @@ public class WxMpMaterialVideoInfoResult implements Serializable {
         this.downUrl = downUrl;
       }
     
    -  public static WxMpMaterialVideoInfoResult fromJson(String json) {
    -    return WxMpGsonBuilder.create().fromJson(json, WxMpMaterialVideoInfoResult.class);
    -  }
    -
       @Override
       public String toString() {
         return "WxMpMaterialVideoInfoResult [title=" + this.title + ", description=" + this.description + ", downUrl=" + this.downUrl + "]";
    diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/menu/WxMpSelfMenuInfo.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/menu/WxMpSelfMenuInfo.java
    index f2c0c4ca..588e8a9c 100644
    --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/menu/WxMpSelfMenuInfo.java
    +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/menu/WxMpSelfMenuInfo.java
    @@ -25,11 +25,6 @@ public class WxMpSelfMenuInfo {
       }
     
       public static class WxMpSelfMenuButton {
    -    @Override
    -    public String toString() {
    -      return ToStringUtils.toSimpleString(this);
    -    }
    -
         /**
          * 
          * 菜单的类型,公众平台官网上能够设置的菜单类型有view(跳转网页)、text(返回文本,下同)、img、photo、video、voice。
    @@ -38,13 +33,11 @@ public class WxMpSelfMenuInfo {
          */
         @SerializedName("type")
         private String type;
    -
         /**
          * 菜单名称
          */
         @SerializedName("name")
         private String name;
    -
         /**
          * 
          * 对于不同的菜单类型,value的值意义不同。
    @@ -62,24 +55,31 @@ public class WxMpSelfMenuInfo {
          */
         @SerializedName("key")
         private String key;
    -
         /**
          * @see #key
          */
         @SerializedName("url")
         private String url;
    -
         /**
          * @see #key
          */
         @SerializedName("value")
         private String value;
    -
         /**
          * 子菜单信息
          */
         @SerializedName("sub_button")
         private SubButtons subButtons;
    +    /**
    +     * 图文消息的信息
    +     */
    +    @SerializedName("news_info")
    +    private NewsInfo newsInfo;
    +
    +    @Override
    +    public String toString() {
    +      return ToStringUtils.toSimpleString(this);
    +    }
     
         public SubButtons getSubButtons() {
           return subButtons;
    @@ -89,30 +89,6 @@ public class WxMpSelfMenuInfo {
           this.subButtons = subButtons;
         }
     
    -    public static class SubButtons {
    -      @Override
    -      public String toString() {
    -        return ToStringUtils.toSimpleString(this);
    -      }
    -
    -      @SerializedName("list")
    -      private List subButtons = new ArrayList<>();
    -
    -      public List getSubButtons() {
    -        return subButtons;
    -      }
    -
    -      public void setSubButtons(List subButtons) {
    -        this.subButtons = subButtons;
    -      }
    -    }
    -
    -    /**
    -     * 图文消息的信息
    -     */
    -    @SerializedName("news_info")
    -    private NewsInfo newsInfo;
    -
         public String getType() {
           return type;
         }
    @@ -161,15 +137,33 @@ public class WxMpSelfMenuInfo {
           this.newsInfo = newsInfo;
         }
     
    -    public static class NewsInfo {
    +    public static class SubButtons {
    +      @SerializedName("list")
    +      private List subButtons = new ArrayList<>();
    +
           @Override
           public String toString() {
             return ToStringUtils.toSimpleString(this);
           }
     
    +      public List getSubButtons() {
    +        return subButtons;
    +      }
    +
    +      public void setSubButtons(List subButtons) {
    +        this.subButtons = subButtons;
    +      }
    +    }
    +
    +    public static class NewsInfo {
           @SerializedName("list")
           private List news = new ArrayList<>();
     
    +      @Override
    +      public String toString() {
    +        return ToStringUtils.toSimpleString(this);
    +      }
    +
           public List getNews() {
             return news;
           }
    @@ -179,54 +173,48 @@ public class WxMpSelfMenuInfo {
           }
     
           public static class NewsInButton {
    -        @Override
    -        public String toString() {
    -          return ToStringUtils.toSimpleString(this);
    -        }
    -
             /**
              * 图文消息的标题
              */
             @SerializedName("title")
             private String title;
    -
             /**
              * 摘要
              */
             @SerializedName("digest")
             private String digest;
    -
             /**
              * 作者
              */
             @SerializedName("author")
             private String author;
    -
             /**
              * show_cover
              * 是否显示封面,0为不显示,1为显示
              */
             @SerializedName("show_cover")
             private Integer showCover;
    -
             /**
              * 封面图片的URL
              */
             @SerializedName("cover_url")
             private String coverUrl;
    -
             /**
              * 正文的URL
              */
             @SerializedName("content_url")
             private String contentUrl;
    -
             /**
              * 原文的URL,若置空则无查看原文入口
              */
             @SerializedName("source_url")
             private String sourceUrl;
     
    +        @Override
    +        public String toString() {
    +          return ToStringUtils.toSimpleString(this);
    +        }
    +
             public String getTitle() {
               return title;
             }
    diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/message/WxMpXmlOutImageMessage.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/message/WxMpXmlOutImageMessage.java
    index 62852ca8..f3a07407 100644
    --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/message/WxMpXmlOutImageMessage.java
    +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/message/WxMpXmlOutImageMessage.java
    @@ -16,6 +16,10 @@ public class WxMpXmlOutImageMessage extends WxMpXmlOutMessage {
       @XStreamConverter(value = XStreamMediaIdConverter.class)
       private String mediaId;
     
    +  public WxMpXmlOutImageMessage() {
    +    this.msgType = WxConsts.XML_MSG_IMAGE;
    +  }
    +
       public String getMediaId() {
         return this.mediaId;
       }
    @@ -24,8 +28,4 @@ public class WxMpXmlOutImageMessage extends WxMpXmlOutMessage {
         this.mediaId = mediaId;
       }
     
    -  public WxMpXmlOutImageMessage() {
    -    this.msgType = WxConsts.XML_MSG_IMAGE;
    -  }
    -
     }
    diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/message/WxMpXmlOutMessage.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/message/WxMpXmlOutMessage.java
    index c0b53d46..ad5d5bd5 100644
    --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/message/WxMpXmlOutMessage.java
    +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/message/WxMpXmlOutMessage.java
    @@ -16,66 +16,20 @@ public abstract class WxMpXmlOutMessage implements Serializable {
       private static final long serialVersionUID = -381382011286216263L;
     
       @XStreamAlias("ToUserName")
    -  @XStreamConverter(value=XStreamCDataConverter.class)
    +  @XStreamConverter(value = XStreamCDataConverter.class)
       protected String toUserName;
     
       @XStreamAlias("FromUserName")
    -  @XStreamConverter(value=XStreamCDataConverter.class)
    +  @XStreamConverter(value = XStreamCDataConverter.class)
       protected String fromUserName;
     
       @XStreamAlias("CreateTime")
       protected Long createTime;
     
       @XStreamAlias("MsgType")
    -  @XStreamConverter(value=XStreamCDataConverter.class)
    +  @XStreamConverter(value = XStreamCDataConverter.class)
       protected String msgType;
     
    -  public String getToUserName() {
    -    return this.toUserName;
    -  }
    -
    -  public void setToUserName(String toUserName) {
    -    this.toUserName = toUserName;
    -  }
    -
    -  public String getFromUserName() {
    -    return this.fromUserName;
    -  }
    -
    -  public void setFromUserName(String fromUserName) {
    -    this.fromUserName = fromUserName;
    -  }
    -
    -  public Long getCreateTime() {
    -    return this.createTime;
    -  }
    -
    -  public void setCreateTime(Long createTime) {
    -    this.createTime = createTime;
    -  }
    -
    -  public String getMsgType() {
    -    return this.msgType;
    -  }
    -
    -  public void setMsgType(String msgType) {
    -    this.msgType = msgType;
    -  }
    -
    -  @SuppressWarnings("unchecked")
    -	public String toXml() {
    -    return XStreamTransformer.toXml((Class) this.getClass(), this);
    -  }
    -
    -  /**
    -   * 转换成加密的xml格式
    -   */
    -  public String toEncryptedXml(WxMpConfigStorage wxMpConfigStorage) {
    -    String plainXml = toXml();
    -    WxMpCryptUtil pc = new WxMpCryptUtil(wxMpConfigStorage);
    -    return pc.encrypt(plainXml);
    -  }
    -
       /**
        * 获得文本消息builder
        */
    @@ -124,4 +78,50 @@ public abstract class WxMpXmlOutMessage implements Serializable {
       public static TransferCustomerServiceBuilder TRANSFER_CUSTOMER_SERVICE() {
         return new TransferCustomerServiceBuilder();
       }
    +
    +  public String getToUserName() {
    +    return this.toUserName;
    +  }
    +
    +  public void setToUserName(String toUserName) {
    +    this.toUserName = toUserName;
    +  }
    +
    +  public String getFromUserName() {
    +    return this.fromUserName;
    +  }
    +
    +  public void setFromUserName(String fromUserName) {
    +    this.fromUserName = fromUserName;
    +  }
    +
    +  public Long getCreateTime() {
    +    return this.createTime;
    +  }
    +
    +  public void setCreateTime(Long createTime) {
    +    this.createTime = createTime;
    +  }
    +
    +  public String getMsgType() {
    +    return this.msgType;
    +  }
    +
    +  public void setMsgType(String msgType) {
    +    this.msgType = msgType;
    +  }
    +
    +  @SuppressWarnings("unchecked")
    +  public String toXml() {
    +    return XStreamTransformer.toXml((Class) this.getClass(), this);
    +  }
    +
    +  /**
    +   * 转换成加密的xml格式
    +   */
    +  public String toEncryptedXml(WxMpConfigStorage wxMpConfigStorage) {
    +    String plainXml = toXml();
    +    WxMpCryptUtil pc = new WxMpCryptUtil(wxMpConfigStorage);
    +    return pc.encrypt(plainXml);
    +  }
     }
    diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/message/WxMpXmlOutMusicMessage.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/message/WxMpXmlOutMusicMessage.java
    index a5b48619..c9bd0036 100644
    --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/message/WxMpXmlOutMusicMessage.java
    +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/message/WxMpXmlOutMusicMessage.java
    @@ -63,23 +63,23 @@ public class WxMpXmlOutMusicMessage extends WxMpXmlOutMessage {
       public static class Music {
     
         @XStreamAlias("Title")
    -    @XStreamConverter(value=XStreamCDataConverter.class)
    +    @XStreamConverter(value = XStreamCDataConverter.class)
         private String title;
     
         @XStreamAlias("Description")
    -    @XStreamConverter(value=XStreamCDataConverter.class)
    +    @XStreamConverter(value = XStreamCDataConverter.class)
         private String description;
     
         @XStreamAlias("ThumbMediaId")
    -    @XStreamConverter(value=XStreamCDataConverter.class)
    +    @XStreamConverter(value = XStreamCDataConverter.class)
         private String thumbMediaId;
     
         @XStreamAlias("MusicUrl")
    -    @XStreamConverter(value=XStreamCDataConverter.class)
    +    @XStreamConverter(value = XStreamCDataConverter.class)
         private String musicUrl;
     
         @XStreamAlias("HQMusicUrl")
    -    @XStreamConverter(value=XStreamCDataConverter.class)
    +    @XStreamConverter(value = XStreamCDataConverter.class)
         private String hqMusicUrl;
     
         public String getTitle() {
    diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/message/WxMpXmlOutNewsMessage.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/message/WxMpXmlOutNewsMessage.java
    index 413a6d7c..1d4fb0c7 100644
    --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/message/WxMpXmlOutNewsMessage.java
    +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/message/WxMpXmlOutNewsMessage.java
    @@ -15,12 +15,10 @@ public class WxMpXmlOutNewsMessage extends WxMpXmlOutMessage {
        *
        */
       private static final long serialVersionUID = -4604402850905714772L;
    -
    -  @XStreamAlias("ArticleCount")
    -  protected int articleCount;
    -
       @XStreamAlias("Articles")
       protected final List articles = new ArrayList<>();
    +  @XStreamAlias("ArticleCount")
    +  protected int articleCount;
     
       public WxMpXmlOutNewsMessage() {
         this.msgType = WxConsts.XML_MSG_NEWS;
    @@ -44,19 +42,19 @@ public class WxMpXmlOutNewsMessage extends WxMpXmlOutMessage {
       public static class Item {
     
         @XStreamAlias("Title")
    -    @XStreamConverter(value=XStreamCDataConverter.class)
    +    @XStreamConverter(value = XStreamCDataConverter.class)
         private String Title;
     
         @XStreamAlias("Description")
    -    @XStreamConverter(value=XStreamCDataConverter.class)
    +    @XStreamConverter(value = XStreamCDataConverter.class)
         private String Description;
     
         @XStreamAlias("PicUrl")
    -    @XStreamConverter(value=XStreamCDataConverter.class)
    +    @XStreamConverter(value = XStreamCDataConverter.class)
         private String PicUrl;
     
         @XStreamAlias("Url")
    -    @XStreamConverter(value=XStreamCDataConverter.class)
    +    @XStreamConverter(value = XStreamCDataConverter.class)
         private String Url;
     
         public String getTitle() {
    diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/message/WxMpXmlOutTextMessage.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/message/WxMpXmlOutTextMessage.java
    index 0719b1ed..877ed260 100644
    --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/message/WxMpXmlOutTextMessage.java
    +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/message/WxMpXmlOutTextMessage.java
    @@ -13,7 +13,7 @@ public class WxMpXmlOutTextMessage extends WxMpXmlOutMessage {
        */
       private static final long serialVersionUID = -3972786455288763361L;
       @XStreamAlias("Content")
    -  @XStreamConverter(value=XStreamCDataConverter.class)
    +  @XStreamConverter(value = XStreamCDataConverter.class)
       private String content;
     
       public WxMpXmlOutTextMessage() {
    diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/message/WxMpXmlOutTransferKefuMessage.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/message/WxMpXmlOutTransferKefuMessage.java
    index b0eece70..1c5f72d6 100644
    --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/message/WxMpXmlOutTransferKefuMessage.java
    +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/message/WxMpXmlOutTransferKefuMessage.java
    @@ -28,7 +28,7 @@ public class WxMpXmlOutTransferKefuMessage extends WxMpXmlOutMessage {
       public static class TransInfo {
     
         @XStreamAlias("KfAccount")
    -    @XStreamConverter(value=XStreamCDataConverter.class)
    +    @XStreamConverter(value = XStreamCDataConverter.class)
         private String kfAccount;
     
         public String getKfAccount() {
    diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/message/WxMpXmlOutVideoMessage.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/message/WxMpXmlOutVideoMessage.java
    index 3c042f6d..adf88490 100644
    --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/message/WxMpXmlOutVideoMessage.java
    +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/message/WxMpXmlOutVideoMessage.java
    @@ -45,18 +45,18 @@ public class WxMpXmlOutVideoMessage extends WxMpXmlOutMessage {
     
     
       @XStreamAlias("Video")
    -    public static class Video {
    +  public static class Video {
     
         @XStreamAlias("MediaId")
    -    @XStreamConverter(value=XStreamCDataConverter.class)
    +    @XStreamConverter(value = XStreamCDataConverter.class)
         private String mediaId;
     
         @XStreamAlias("Title")
    -    @XStreamConverter(value=XStreamCDataConverter.class)
    +    @XStreamConverter(value = XStreamCDataConverter.class)
         private String title;
     
         @XStreamAlias("Description")
    -    @XStreamConverter(value=XStreamCDataConverter.class)
    +    @XStreamConverter(value = XStreamCDataConverter.class)
         private String description;
     
         public String getMediaId() {
    diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMassSendResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMassSendResult.java
    index ffb8f026..9341fdfb 100644
    --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMassSendResult.java
    +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMassSendResult.java
    @@ -13,8 +13,8 @@ import java.io.Serializable;
      * http://mp.weixin.qq.com/wiki/index.php?title=高级群发接口#.E4.BA.8B.E4.BB.B6.E6.8E.A8.E9.80.81.E7.BE.A4.E5.8F.91.E7.BB.93.E6.9E.9C
      *
      * 
    - * @author chanjarster * + * @author chanjarster */ public class WxMpMassSendResult implements Serializable { private static final long serialVersionUID = -4816336807575562818L; @@ -23,6 +23,10 @@ public class WxMpMassSendResult implements Serializable { private String msgId; private String msgDataId; + public static WxMpMassSendResult fromJson(String json) { + return WxMpGsonBuilder.create().fromJson(json, WxMpMassSendResult.class); + } + public String getErrorCode() { return this.errorCode; } @@ -55,10 +59,6 @@ public class WxMpMassSendResult implements Serializable { this.msgDataId = msgDataId; } - public static WxMpMassSendResult fromJson(String json) { - return WxMpGsonBuilder.create().fromJson(json, WxMpMassSendResult.class); - } - @Override public String toString() { return ToStringUtils.toSimpleString(this); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMassUploadResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMassUploadResult.java index 6a4f88d8..9862c43c 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMassUploadResult.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMassUploadResult.java @@ -9,19 +9,23 @@ import java.io.Serializable; * 上传群发用的素材的结果 * 视频和图文消息需要在群发前上传素材 *
    - * @author chanjarster * + * @author chanjarster */ public class WxMpMassUploadResult implements Serializable { /** - * + * */ private static final long serialVersionUID = 6568157943644994029L; private String type; private String mediaId; private long createdAt; + public static WxMpMassUploadResult fromJson(String json) { + return WxMpGsonBuilder.create().fromJson(json, WxMpMassUploadResult.class); + } + public String getType() { return this.type; } @@ -46,10 +50,6 @@ public class WxMpMassUploadResult implements Serializable { this.createdAt = createdAt; } - public static WxMpMassUploadResult fromJson(String json) { - return WxMpGsonBuilder.create().fromJson(json, WxMpMassUploadResult.class); - } - @Override public String toString() { return "WxUploadResult [type=" + this.type + ", media_id=" + this.mediaId + ", created_at=" + this.createdAt + "]"; diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpOAuth2AccessToken.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpOAuth2AccessToken.java index d38317ce..b485710a 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpOAuth2AccessToken.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpOAuth2AccessToken.java @@ -1,13 +1,13 @@ package me.chanjar.weixin.mp.bean.result; -import java.io.Serializable; - import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; +import java.io.Serializable; + public class WxMpOAuth2AccessToken implements Serializable { /** - * + * */ private static final long serialVersionUID = -1345910558078620805L; @@ -23,6 +23,10 @@ public class WxMpOAuth2AccessToken implements Serializable { private String unionId; + public static WxMpOAuth2AccessToken fromJson(String json) { + return WxMpGsonBuilder.create().fromJson(json, WxMpOAuth2AccessToken.class); + } + public String getRefreshToken() { return this.refreshToken; } @@ -71,19 +75,15 @@ public class WxMpOAuth2AccessToken implements Serializable { this.unionId = unionId; } - public static WxMpOAuth2AccessToken fromJson(String json) { - return WxMpGsonBuilder.create().fromJson(json, WxMpOAuth2AccessToken.class); - } - @Override public String toString() { return "WxMpOAuth2AccessToken{" + - "accessToken='" + this.accessToken + '\'' + - ", expiresTime=" + this.expiresIn + - ", refreshToken='" + this.refreshToken + '\'' + - ", openId='" + this.openId + '\'' + - ", scope='" + this.scope + '\'' + - ", unionId='" + this.unionId + '\'' + - '}'; + "accessToken='" + this.accessToken + '\'' + + ", expiresTime=" + this.expiresIn + + ", refreshToken='" + this.refreshToken + '\'' + + ", openId='" + this.openId + '\'' + + ", scope='" + this.scope + '\'' + + ", unionId='" + this.unionId + '\'' + + '}'; } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpQrCodeTicket.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpQrCodeTicket.java index a2917ecc..fc7d0713 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpQrCodeTicket.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpQrCodeTicket.java @@ -6,19 +6,23 @@ import java.io.Serializable; /** * 换取二维码的Ticket - * + * * @author chanjarster */ public class WxMpQrCodeTicket implements Serializable { - + /** - * + * */ private static final long serialVersionUID = 5777119669111011584L; protected String ticket; protected int expire_seconds = -1; protected String url; + public static WxMpQrCodeTicket fromJson(String json) { + return WxMpGsonBuilder.INSTANCE.create().fromJson(json, WxMpQrCodeTicket.class); + } + public String getTicket() { return this.ticket; } @@ -46,10 +50,6 @@ public class WxMpQrCodeTicket implements Serializable { this.url = url; } - public static WxMpQrCodeTicket fromJson(String json) { - return WxMpGsonBuilder.INSTANCE.create().fromJson(json, WxMpQrCodeTicket.class); - } - @Override public String toString() { return WxMpGsonBuilder.INSTANCE.create().toJson(this); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpSemanticQueryResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpSemanticQueryResult.java index c8a01d3e..8fd5442c 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpSemanticQueryResult.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpSemanticQueryResult.java @@ -6,7 +6,7 @@ import java.io.Serializable; /** * 语义理解查询结果对象 - * + *

    * http://mp.weixin.qq.com/wiki/index.php?title=语义理解 * * @author Daniel Qian @@ -14,7 +14,7 @@ import java.io.Serializable; public class WxMpSemanticQueryResult implements Serializable { /** - * + * */ private static final long serialVersionUID = 4811088544804441365L; private String query; @@ -24,6 +24,10 @@ public class WxMpSemanticQueryResult implements Serializable { private String answer; private String text; + public static WxMpSemanticQueryResult fromJson(String json) { + return WxMpGsonBuilder.create().fromJson(json, WxMpSemanticQueryResult.class); + } + public String getQuery() { return this.query; } @@ -72,8 +76,4 @@ public class WxMpSemanticQueryResult implements Serializable { this.text = text; } - public static WxMpSemanticQueryResult fromJson(String json) { - return WxMpGsonBuilder.create().fromJson(json, WxMpSemanticQueryResult.class); - } - } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpUser.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpUser.java index 7131de5c..f2ba9268 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpUser.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpUser.java @@ -12,8 +12,8 @@ import java.util.List; /** * 微信用户信息 - * @author chanjarster * + * @author chanjarster */ public class WxMpUser implements Serializable { @@ -34,6 +34,18 @@ public class WxMpUser implements Serializable { private Integer groupId; private Long[] tagIds; + public static WxMpUser fromJson(String json) { + return WxMpGsonBuilder.INSTANCE.create().fromJson(json, WxMpUser.class); + } + + public static List fromJsonList(String json) { + Type collectionType = new TypeToken>() { + }.getType(); + Gson gson = WxMpGsonBuilder.INSTANCE.create(); + JsonObject jsonObject = gson.fromJson(json, JsonObject.class); + return gson.fromJson(jsonObject.get("user_info_list"), collectionType); + } + public Boolean getSubscribe() { return this.subscribe; } @@ -115,7 +127,7 @@ public class WxMpUser implements Serializable { } /** - *只有在将公众号绑定到微信开放平台帐号后,才会出现该字段。 + * 只有在将公众号绑定到微信开放平台帐号后,才会出现该字段。 */ public String getUnionId() { return this.unionId; @@ -158,18 +170,6 @@ public class WxMpUser implements Serializable { this.tagIds = tagIds; } - public static WxMpUser fromJson(String json) { - return WxMpGsonBuilder.INSTANCE.create().fromJson(json, WxMpUser.class); - } - - public static List fromJsonList(String json) { - Type collectionType = new TypeToken>() { - }.getType(); - Gson gson = WxMpGsonBuilder.INSTANCE.create(); - JsonObject jsonObject = gson.fromJson(json, JsonObject.class); - return gson.fromJson(jsonObject.get("user_info_list"), collectionType); - } - @Override public String toString() { return ToStringUtils.toSimpleString(this); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpUserList.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpUserList.java index 87ce18cd..2f630e5b 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpUserList.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpUserList.java @@ -7,8 +7,8 @@ import java.util.List; /** * 关注者列表 - * @author chanjarster * + * @author chanjarster */ public class WxMpUserList { @@ -16,37 +16,45 @@ public class WxMpUserList { protected int count = -1; protected List openids = new ArrayList<>(); protected String nextOpenid; + + public static WxMpUserList fromJson(String json) { + return WxMpGsonBuilder.INSTANCE.create().fromJson(json, WxMpUserList.class); + } + public long getTotal() { return this.total; } + public void setTotal(long total) { this.total = total; } + public int getCount() { return this.count; } + public void setCount(int count) { this.count = count; } + public List getOpenids() { return this.openids; } + public void setOpenids(List openids) { this.openids = openids; } + public String getNextOpenid() { return this.nextOpenid; } + public void setNextOpenid(String nextOpenid) { this.nextOpenid = nextOpenid; } - public static WxMpUserList fromJson(String json) { - return WxMpGsonBuilder.INSTANCE.create().fromJson(json, WxMpUserList.class); - } - @Override public String toString() { - return WxMpGsonBuilder.INSTANCE.create().toJson(this); + return WxMpGsonBuilder.INSTANCE.create().toJson(this); } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/store/WxMpStoreBaseInfo.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/store/WxMpStoreBaseInfo.java index 91d52d2e..b385fbd0 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/store/WxMpStoreBaseInfo.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/store/WxMpStoreBaseInfo.java @@ -12,200 +12,177 @@ import java.util.List; /** * 门店基础信息 + * * @author binarywang(Binary Wang) * Created by Binary Wang on 2016-09-23. */ public class WxMpStoreBaseInfo { - @Override - public String toString() { - return ToStringUtils.toSimpleString(this); - } - - public static WxMpStoreBaseInfo fromJson(String json) { - return WxMpGsonBuilder.create().fromJson(json, WxMpStoreBaseInfo.class); - } - - public String toJson() { - JsonElement base_info = WxMpGsonBuilder.create().toJsonTree(this); - JsonObject jsonObject = new JsonObject(); - jsonObject.add("base_info", base_info); - JsonObject business = new JsonObject(); - business.add("business", jsonObject); - return business.toString(); - } - - public static class WxMpStorePhoto { - /** - * 照片url - */ - @SerializedName("photo_url") - private String photoUrl; - } - /** - * sid - * 商户自己的id,用于后续审核通过收到poi_id 的通知时,做对应关系。请商户自己保证唯一识别性 - */ + * sid + * 商户自己的id,用于后续审核通过收到poi_id 的通知时,做对应关系。请商户自己保证唯一识别性 + */ @SerializedName("sid") private String sid; - /** - * business_name - * 门店名称(仅为商户名,如:国美、麦当劳,不应包含地区、地址、分店名等信息,错误示例:北京国美) - * 不能为空,15个汉字或30个英文字符内 - */ + * business_name + * 门店名称(仅为商户名,如:国美、麦当劳,不应包含地区、地址、分店名等信息,错误示例:北京国美) + * 不能为空,15个汉字或30个英文字符内 + */ @Required @SerializedName("business_name") private String businessName; - /** - * branch_name - * 分店名称(不应包含地区信息,不应与门店名有重复,错误示例:北京王府井店) - * 10个字以内 - */ + * branch_name + * 分店名称(不应包含地区信息,不应与门店名有重复,错误示例:北京王府井店) + * 10个字以内 + */ @Required @SerializedName("branch_name") private String branchName; - /** - * province - * 门店所在的省份(直辖市填城市名,如:北京市) - * 10个字以内 - */ + * province + * 门店所在的省份(直辖市填城市名,如:北京市) + * 10个字以内 + */ @Required @SerializedName("province") private String province; - /** - * city - * 门店所在的城市 - * 10个字以内 - */ + * city + * 门店所在的城市 + * 10个字以内 + */ @Required @SerializedName("city") private String city; - /** - * district - * 门店所在地区 - * 10个字以内 - */ + * district + * 门店所在地区 + * 10个字以内 + */ @Required @SerializedName("district") private String district; - /** - * address - * 门店所在的详细街道地址(不要填写省市信息) - * (东莞等没有“区”行政区划的城市,该字段可不必填写。其余城市必填。) - */ + * address + * 门店所在的详细街道地址(不要填写省市信息) + * (东莞等没有“区”行政区划的城市,该字段可不必填写。其余城市必填。) + */ @Required @SerializedName("address") private String address; - /** - * telephone - * 门店的电话(纯数字,区号、分机号均由“-”隔开) - */ + * telephone + * 门店的电话(纯数字,区号、分机号均由“-”隔开) + */ @Required @SerializedName("telephone") private String telephone; - /** - * categories - * 门店的类型(不同级分类用“,”隔开,如:美食,川菜,火锅。详细分类参见附件:微信门店类目表) - */ + * categories + * 门店的类型(不同级分类用“,”隔开,如:美食,川菜,火锅。详细分类参见附件:微信门店类目表) + */ @Required @SerializedName("categories") private String[] categories; - /** - * offsetType - * 坐标类型,1 为火星坐标(目前只能选1) - */ + * offsetType + * 坐标类型,1 为火星坐标(目前只能选1) + */ @Required @SerializedName("offset_type") private Integer offsetType = 1; - /** - * longitude - * 门店所在地理位置的经度 - */ + * longitude + * 门店所在地理位置的经度 + */ @Required @SerializedName("longitude") private BigDecimal longitude; - /** - * latitude - * 门店所在地理位置的纬度(经纬度均为火星坐标,最好选用腾讯地图标记的坐标) - */ + * latitude + * 门店所在地理位置的纬度(经纬度均为火星坐标,最好选用腾讯地图标记的坐标) + */ @Required @SerializedName("latitude") private BigDecimal latitude; - /** - * photo_list - * 图片列表,url 形式,可以有多张图片,尺寸为 640*340px。必须为上一接口生成的url。 - * 图片内容不允许与门店不相关,不允许为二维码、员工合照(或模特肖像)、营业执照、无门店正门的街景、地图截图、公交地铁站牌、菜单截图等 - */ + * photo_list + * 图片列表,url 形式,可以有多张图片,尺寸为 640*340px。必须为上一接口生成的url。 + * 图片内容不允许与门店不相关,不允许为二维码、员工合照(或模特肖像)、营业执照、无门店正门的街景、地图截图、公交地铁站牌、菜单截图等 + */ @SerializedName("photo_list") private List photos; - /** - * recommend - * 推荐品,餐厅可为推荐菜;酒店为推荐套房;景点为推荐游玩景点等,针对自己行业的推荐内容 - * 200字以内 - */ + * recommend + * 推荐品,餐厅可为推荐菜;酒店为推荐套房;景点为推荐游玩景点等,针对自己行业的推荐内容 + * 200字以内 + */ @SerializedName("recommend") private String recommend; - /** - * special - * 特色服务,如免费wifi,免费停车,送货上门等商户能提供的特色功能或服务 - */ + * special + * 特色服务,如免费wifi,免费停车,送货上门等商户能提供的特色功能或服务 + */ @SerializedName("special") private String special; - /** - * introduction - * 商户简介,主要介绍商户信息等 - * 300字以内 - */ + * introduction + * 商户简介,主要介绍商户信息等 + * 300字以内 + */ @SerializedName("introduction") private String introduction; - /** * open_time - * 营业时间,24 小时制表示,用“-”连接,如 8:00-20:00 - */ + * 营业时间,24 小时制表示,用“-”连接,如 8:00-20:00 + */ @SerializedName("open_time") private String openTime; - /** - * avg_price - * 人均价格,大于0 的整数 - */ + * avg_price + * 人均价格,大于0 的整数 + */ @SerializedName("avg_price") private Integer avgPrice; - /** * 门店是否可用状态。1 表示系统错误、2 表示审核中、3 审核通过、4 审核驳回。当该字段为1、2、4 状态时,poi_id 为空 */ @SerializedName("available_state") private Integer availableState; - /** * 扩展字段是否正在更新中。1 表示扩展字段正在更新中,尚未生效,不允许再次更新; 0 表示扩展字段没有在更新中或更新已生效,可以再次更新 */ @SerializedName("update_status") private Integer updateStatus; - /** * 门店poi id */ @SerializedName("poi_id") private String poiId; + public static WxMpStoreBaseInfo fromJson(String json) { + return WxMpGsonBuilder.create().fromJson(json, WxMpStoreBaseInfo.class); + } + + public static WxMpStoreBaseInfoBuilder builder() { + return new WxMpStoreBaseInfoBuilder(); + } + + @Override + public String toString() { + return ToStringUtils.toSimpleString(this); + } + + public String toJson() { + JsonElement base_info = WxMpGsonBuilder.create().toJsonTree(this); + JsonObject jsonObject = new JsonObject(); + jsonObject.add("base_info", base_info); + JsonObject business = new JsonObject(); + business.add("business", jsonObject); + return business.toString(); + } + public String getSid() { return this.sid; } @@ -374,8 +351,12 @@ public class WxMpStoreBaseInfo { this.poiId = poiId; } - public static WxMpStoreBaseInfoBuilder builder() { - return new WxMpStoreBaseInfoBuilder(); + public static class WxMpStorePhoto { + /** + * 照片url + */ + @SerializedName("photo_url") + private String photoUrl; } public static class WxMpStoreBaseInfoBuilder { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/store/WxMpStoreInfo.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/store/WxMpStoreInfo.java index 1450bc3c..8f0b0401 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/store/WxMpStoreInfo.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/store/WxMpStoreInfo.java @@ -4,14 +4,14 @@ import com.google.gson.annotations.SerializedName; import me.chanjar.weixin.common.util.ToStringUtils; public class WxMpStoreInfo { + @SerializedName("base_info") + private WxMpStoreBaseInfo baseInfo; + @Override public String toString() { return ToStringUtils.toSimpleString(this); } - @SerializedName("base_info") - private WxMpStoreBaseInfo baseInfo; - public WxMpStoreBaseInfo getBaseInfo() { return this.baseInfo; } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/store/WxMpStoreListResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/store/WxMpStoreListResult.java index f9cc3fbe..3b2c2fc1 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/store/WxMpStoreListResult.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/store/WxMpStoreListResult.java @@ -8,44 +8,41 @@ import java.util.List; /** * 门店列表结果类 + * * @author binarywang(Binary Wang) * Created by Binary Wang on 2016-09-27. - * */ public class WxMpStoreListResult { - @Override - public String toString() { - return ToStringUtils.toSimpleString(this); - } - - public static WxMpStoreListResult fromJson(String json) { - return WxMpGsonBuilder.create().fromJson(json, WxMpStoreListResult.class); - } - /** * 错误码,0为正常 */ @SerializedName("errcode") private Integer errCode; - /** * 错误信息 */ @SerializedName("errmsg") private String errMsg; - /** * 门店信息列表 */ @SerializedName("business_list") private List businessList; - /** * 门店信息总数 */ @SerializedName("total_count") private Integer totalCount; + public static WxMpStoreListResult fromJson(String json) { + return WxMpGsonBuilder.create().fromJson(json, WxMpStoreListResult.class); + } + + @Override + public String toString() { + return ToStringUtils.toSimpleString(this); + } + public Integer getTotalCount() { return this.totalCount; } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/tag/WxTagListUser.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/tag/WxTagListUser.java index e1307be7..952b764c 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/tag/WxTagListUser.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/tag/WxTagListUser.java @@ -8,42 +8,41 @@ import java.util.List; /** * 获取标签下粉丝列表的结果对象 + * * @author binarywang(Binary Wang) * Created by Binary Wang on 2016-09-19. */ public class WxTagListUser { - public static WxTagListUser fromJson(String json) { - return WxMpGsonBuilder.create().fromJson(json,WxTagListUser.class); - } - - public String toJson() { - return WxMpGsonBuilder.create().toJson(this); - } - - @Override - public String toString() { - return ToStringUtils.toSimpleString(this); - } - /** - *"count":2,这次获取的粉丝数量 + * "count":2,这次获取的粉丝数量 */ @SerializedName("count") private Integer count; - /** - *"data" 粉丝列表 + * "data" 粉丝列表 */ @SerializedName("data") private WxTagListUserData data; - /** - *"next_openid" 拉取列表最后一个用户的openid + * "next_openid" 拉取列表最后一个用户的openid */ @SerializedName("next_openid") private String nextOpenid; + public static WxTagListUser fromJson(String json) { + return WxMpGsonBuilder.create().fromJson(json, WxTagListUser.class); + } + + public String toJson() { + return WxMpGsonBuilder.create().toJson(this); + } + + @Override + public String toString() { + return ToStringUtils.toSimpleString(this); + } + public Integer getCount() { return this.count; } @@ -69,17 +68,17 @@ public class WxTagListUser { } public static class WxTagListUserData { - @Override - public String toString() { - return ToStringUtils.toSimpleString(this); - } - /** * openid 列表 */ @SerializedName("openid") private List openidList; + @Override + public String toString() { + return ToStringUtils.toSimpleString(this); + } + public List getOpenidList() { return this.openidList; } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/tag/WxUserTag.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/tag/WxUserTag.java index 6554c261..59d2458f 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/tag/WxUserTag.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/tag/WxUserTag.java @@ -9,6 +9,7 @@ import java.util.List; /** * 用户标签对象 + * * @author binarywang(Binary Wang) * Created by Binary Wang on 2016/9/2. */ @@ -28,6 +29,19 @@ public class WxUserTag { */ private Integer count; + public static WxUserTag fromJson(String json) { + return WxMpGsonBuilder.create().fromJson( + new JsonParser().parse(json).getAsJsonObject().get("tag"), + WxUserTag.class); + } + + public static List listFromJson(String json) { + return WxMpGsonBuilder.create().fromJson( + new JsonParser().parse(json).getAsJsonObject().get("tags"), + new TypeToken>() { + }.getType()); + } + public String getName() { return this.name; } @@ -52,18 +66,6 @@ public class WxUserTag { this.id = id; } - public static WxUserTag fromJson(String json) { - return WxMpGsonBuilder.create().fromJson( - new JsonParser().parse(json).getAsJsonObject().get("tag"), - WxUserTag.class); - } - - public static List listFromJson(String json) { - return WxMpGsonBuilder.create().fromJson( - new JsonParser().parse(json).getAsJsonObject().get("tags"), - new TypeToken>(){}.getType()); - } - public String toJson() { return WxMpGsonBuilder.create().toJson(this); } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/template/WxMpTemplate.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/template/WxMpTemplate.java index 368284f2..38761f3d 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/template/WxMpTemplate.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/template/WxMpTemplate.java @@ -18,53 +18,36 @@ import java.util.List; public class WxMpTemplate { private static final JsonParser JSON_PARSER = new JsonParser(); - - public static List fromJson(String json) { - return WxMpGsonBuilder.create().fromJson(JSON_PARSER.parse(json).getAsJsonObject().get("template_list"), - new TypeToken>() { - }.getType()); - } - - @Override - public String toString() { - return ToStringUtils.toSimpleString(this); - } - /** * template_id * 模板ID */ @SerializedName("template_id") private String templateId; - /** * title * 模板标题 */ @SerializedName("title") private String title; - /** * primary_industry * 模板所属行业的一级行业 */ @SerializedName("primary_industry") private String primaryIndustry; - /** * deputy_industry * 模板所属行业的二级行业 */ @SerializedName("deputy_industry") private String deputyIndustry; - /** * content * 模板内容 */ @SerializedName("content") private String content; - /** * example * 模板示例 @@ -72,6 +55,17 @@ public class WxMpTemplate { @SerializedName("example") private String example; + public static List fromJson(String json) { + return WxMpGsonBuilder.create().fromJson(JSON_PARSER.parse(json).getAsJsonObject().get("template_list"), + new TypeToken>() { + }.getType()); + } + + @Override + public String toString() { + return ToStringUtils.toSimpleString(this); + } + public String getTemplateId() { return this.templateId; } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/template/WxMpTemplateIndustry.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/template/WxMpTemplateIndustry.java index 6d0db1ab..63576fc2 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/template/WxMpTemplateIndustry.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/template/WxMpTemplateIndustry.java @@ -22,6 +22,35 @@ public class WxMpTemplateIndustry implements Serializable { this.secondIndustry = secondIndustry; } + public static WxMpTemplateIndustry fromJson(String json) { + return WxMpGsonBuilder.create().fromJson(json, WxMpTemplateIndustry.class); + } + + @Override + public String toString() { + return ToStringUtils.toSimpleString(this); + } + + public String toJson() { + return WxMpGsonBuilder.create().toJson(this); + } + + public Industry getPrimaryIndustry() { + return this.primaryIndustry; + } + + public void setPrimaryIndustry(Industry primaryIndustry) { + this.primaryIndustry = primaryIndustry; + } + + public Industry getSecondIndustry() { + return this.secondIndustry; + } + + public void setSecondIndustry(Industry secondIndustry) { + this.secondIndustry = secondIndustry; + } + /** * @author miller * 官方文档中,创建和获取的数据结构不一样。所以采用冗余字段的方式,实现相应的接口 @@ -74,33 +103,4 @@ public class WxMpTemplateIndustry implements Serializable { this.secondClass = secondClass; } } - - @Override - public String toString() { - return ToStringUtils.toSimpleString(this); - } - - public static WxMpTemplateIndustry fromJson(String json) { - return WxMpGsonBuilder.create().fromJson(json, WxMpTemplateIndustry.class); - } - - public String toJson() { - return WxMpGsonBuilder.create().toJson(this); - } - - public Industry getPrimaryIndustry() { - return this.primaryIndustry; - } - - public void setPrimaryIndustry(Industry primaryIndustry) { - this.primaryIndustry = primaryIndustry; - } - - public Industry getSecondIndustry() { - return this.secondIndustry; - } - - public void setSecondIndustry(Industry secondIndustry) { - this.secondIndustry = secondIndustry; - } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/template/WxMpTemplateMessage.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/template/WxMpTemplateMessage.java index f70090ef..70034a63 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/template/WxMpTemplateMessage.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/template/WxMpTemplateMessage.java @@ -32,6 +32,7 @@ public class WxMpTemplateMessage implements Serializable { private String url; /** * 模板跳转链接 + * * @see #url */ private MiniProgram miniProgram; @@ -44,6 +45,10 @@ public class WxMpTemplateMessage implements Serializable { public WxMpTemplateMessage() { } + public static WxMpTemplateMessageBuilder builder() { + return new WxMpTemplateMessageBuilder(); + } + public String getToUser() { return this.toUser; } @@ -92,10 +97,6 @@ public class WxMpTemplateMessage implements Serializable { return WxMpGsonBuilder.INSTANCE.create().toJson(this); } - public static WxMpTemplateMessageBuilder builder() { - return new WxMpTemplateMessageBuilder(); - } - public static class MiniProgram { private String appid; private String pagePath; diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/kefu/BaseBuilder.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/kefu/BaseBuilder.java index 3e40d178..efd20e0d 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/kefu/BaseBuilder.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/kefu/BaseBuilder.java @@ -7,7 +7,7 @@ public class BaseBuilder { protected String toUser; @SuppressWarnings("unchecked") - public T toUser(String toUser) { + public T toUser(String toUser) { this.toUser = toUser; return (T) this; } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/kefu/ImageBuilder.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/kefu/ImageBuilder.java index 9533f5b3..24d8aaba 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/kefu/ImageBuilder.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/kefu/ImageBuilder.java @@ -8,8 +8,8 @@ import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage; *

      * 用法: WxMpKefuMessage m = WxMpKefuMessage.IMAGE().mediaId(...).toUser(...).build();
      * 
    - * @author chanjarster * + * @author chanjarster */ public final class ImageBuilder extends BaseBuilder { private String mediaId; diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/kefu/MpNewsBuilder.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/kefu/MpNewsBuilder.java index 615802b3..b8fac102 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/kefu/MpNewsBuilder.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/kefu/MpNewsBuilder.java @@ -9,8 +9,8 @@ import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage; * 用法: * WxMpKefuMessage m = WxMpKefuMessage.NEWS().mediaId("xxxxx").toUser(...).build(); *
    - * @author Binary Wang * + * @author Binary Wang */ public final class MpNewsBuilder extends BaseBuilder { private String mediaId; diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/kefu/NewsBuilder.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/kefu/NewsBuilder.java index 900babb5..1626f77e 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/kefu/NewsBuilder.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/kefu/NewsBuilder.java @@ -12,8 +12,8 @@ import java.util.List; * 用法: * WxMpKefuMessage m = WxMpKefuMessage.NEWS().addArticle(article).toUser(...).build(); *
    - * @author chanjarster * + * @author chanjarster */ public final class NewsBuilder extends BaseBuilder { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/kefu/TextBuilder.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/kefu/TextBuilder.java index 9e5f9384..6d9100e9 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/kefu/TextBuilder.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/kefu/TextBuilder.java @@ -8,8 +8,8 @@ import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage; *
      * 用法: WxMpKefuMessage m = WxMpKefuMessage.TEXT().content(...).toUser(...).build();
      * 
    - * @author chanjarster * + * @author chanjarster */ public final class TextBuilder extends BaseBuilder { private String content; diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/kefu/VideoBuilder.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/kefu/VideoBuilder.java index 13ade68c..d7d3772b 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/kefu/VideoBuilder.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/kefu/VideoBuilder.java @@ -14,8 +14,8 @@ import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage; * .toUser(...) * .build(); * - * @author chanjarster * + * @author chanjarster */ public final class VideoBuilder extends BaseBuilder { private String mediaId; diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/kefu/VoiceBuilder.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/kefu/VoiceBuilder.java index c9cb32b2..9fa92f21 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/kefu/VoiceBuilder.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/kefu/VoiceBuilder.java @@ -8,8 +8,8 @@ import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage; *
      * 用法: WxMpKefuMessage m = WxMpKefuMessage.VOICE().mediaId(...).toUser(...).build();
      * 
    - * @author chanjarster * + * @author chanjarster */ public final class VoiceBuilder extends BaseBuilder { private String mediaId; diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/kefu/WxCardBuilder.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/kefu/WxCardBuilder.java index e600df6c..c9eacf0c 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/kefu/WxCardBuilder.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/kefu/WxCardBuilder.java @@ -8,8 +8,8 @@ import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage; *
      * 用法: WxMpKefuMessage m = WxMpKefuMessage.WXCARD().cardId(...).toUser(...).build();
      * 
    - * @author mgcnrx11 * + * @author mgcnrx11 */ public final class WxCardBuilder extends BaseBuilder { private String cardId; diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/outxml/BaseBuilder.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/outxml/BaseBuilder.java index 60cf675d..5b199cc5 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/outxml/BaseBuilder.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/outxml/BaseBuilder.java @@ -9,13 +9,13 @@ public abstract class BaseBuilder { protected String fromUserName; @SuppressWarnings("unchecked") - public BuilderType toUser(String touser) { + public BuilderType toUser(String touser) { this.toUserName = touser; return (BuilderType) this; } @SuppressWarnings("unchecked") - public BuilderType fromUser(String fromusername) { + public BuilderType fromUser(String fromusername) { this.fromUserName = fromusername; return (BuilderType) this; } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/outxml/ImageBuilder.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/outxml/ImageBuilder.java index 0bf441bf..6ce0ce91 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/outxml/ImageBuilder.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/outxml/ImageBuilder.java @@ -4,6 +4,7 @@ import me.chanjar.weixin.mp.bean.message.WxMpXmlOutImageMessage; /** * 图片消息builder + * * @author chanjarster */ public final class ImageBuilder extends BaseBuilder { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/outxml/NewsBuilder.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/outxml/NewsBuilder.java index 1936c5f5..4f9e22e6 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/outxml/NewsBuilder.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/outxml/NewsBuilder.java @@ -7,6 +7,7 @@ import java.util.List; /** * 图文消息builder + * * @author chanjarster */ public final class NewsBuilder extends BaseBuilder { @@ -21,7 +22,7 @@ public final class NewsBuilder extends BaseBuilder { private String content; diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/outxml/TransferCustomerServiceBuilder.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/outxml/TransferCustomerServiceBuilder.java index f025c7a8..bc018e8f 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/outxml/TransferCustomerServiceBuilder.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/builder/outxml/TransferCustomerServiceBuilder.java @@ -23,7 +23,7 @@ public final class TransferCustomerServiceBuilder extends BaseBuilder { @@ -17,10 +17,12 @@ public final class VideoBuilder extends BaseBuilder { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/constant/WxMpEventConstants.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/constant/WxMpEventConstants.java index 77058bad..503367cf 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/constant/WxMpEventConstants.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/constant/WxMpEventConstants.java @@ -41,7 +41,7 @@ public class WxMpEventConstants { * 卡券转赠事件 */ public static final String USER_GIFTING_CARD = "user_gifting_card"; - + /** * 库存报警 */ diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/crypto/WxMpCryptUtil.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/crypto/WxMpCryptUtil.java index 39165b5c..d95e8f8f 100755 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/crypto/WxMpCryptUtil.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/crypto/WxMpCryptUtil.java @@ -1,41 +1,45 @@ -/** - * 对公众平台发送给公众账号的消息加解密示例代码. - * - * @copyright Copyright (c) 1998-2014 Tencent Inc. - */ - -// ------------------------------------------------------------------------ - -/** - * 针对org.apache.commons.codec.binary.Base64, - * 需要导入架包commons-codec-1.9(或commons-codec-1.8等其他版本) - * 官方下载地址:http://commons.apache.org/proper/commons-codec/download_codec.cgi - */ -package me.chanjar.weixin.mp.util.crypto; - -import me.chanjar.weixin.mp.api.WxMpConfigStorage; -import org.apache.commons.codec.binary.Base64; - -public class WxMpCryptUtil extends me.chanjar.weixin.common.util.crypto.WxCryptUtil { - - /** - * 构造函数 - * - * @param wxMpConfigStorage - */ - public WxMpCryptUtil(WxMpConfigStorage wxMpConfigStorage) { - /* - * @param token 公众平台上,开发者设置的token - * @param encodingAesKey 公众平台上,开发者设置的EncodingAESKey - * @param appId 公众平台appid - */ - String encodingAesKey = wxMpConfigStorage.getAesKey(); - String token = wxMpConfigStorage.getToken(); - String appId = wxMpConfigStorage.getAppId(); - - this.token = token; - this.appidOrCorpid = appId; - this.aesKey = Base64.decodeBase64(encodingAesKey + "="); - } - -} +/** + * 对公众平台发送给公众账号的消息加解密示例代码. + * + * @copyright Copyright (c) 1998-2014 Tencent Inc. + *

    + * 针对org.apache.commons.codec.binary.Base64, + * 需要导入架包commons-codec-1.9(或commons-codec-1.8等其他版本) + * 官方下载地址:http://commons.apache.org/proper/commons-codec/download_codec.cgi + */ + +// ------------------------------------------------------------------------ + +/** + * 针对org.apache.commons.codec.binary.Base64, + * 需要导入架包commons-codec-1.9(或commons-codec-1.8等其他版本) + * 官方下载地址:http://commons.apache.org/proper/commons-codec/download_codec.cgi + */ +package me.chanjar.weixin.mp.util.crypto; + +import me.chanjar.weixin.mp.api.WxMpConfigStorage; +import org.apache.commons.codec.binary.Base64; + +public class WxMpCryptUtil extends me.chanjar.weixin.common.util.crypto.WxCryptUtil { + + /** + * 构造函数 + * + * @param wxMpConfigStorage + */ + public WxMpCryptUtil(WxMpConfigStorage wxMpConfigStorage) { + /* + * @param token 公众平台上,开发者设置的token + * @param encodingAesKey 公众平台上,开发者设置的EncodingAESKey + * @param appId 公众平台appid + */ + String encodingAesKey = wxMpConfigStorage.getAesKey(); + String token = wxMpConfigStorage.getToken(); + String appId = wxMpConfigStorage.getAppId(); + + this.token = token; + this.appidOrCorpid = appId; + this.aesKey = Base64.decodeBase64(encodingAesKey + "="); + } + +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialDeleteRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialDeleteRequestExecutor.java index 6bd467c0..307f55ff 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialDeleteRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialDeleteRequestExecutor.java @@ -1,43 +1,20 @@ package me.chanjar.weixin.mp.util.http; -import jodd.http.HttpConnectionProvider; -import jodd.http.HttpRequest; -import jodd.http.HttpResponse; -import jodd.http.ProxyInfo; -import me.chanjar.weixin.common.bean.result.WxError; -import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.common.util.http.RequestExecutor; import me.chanjar.weixin.common.util.http.RequestHttp; -import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; - -import me.chanjar.weixin.common.util.http.okhttp.OkhttpProxyInfo; - -import me.chanjar.weixin.common.util.json.WxGsonBuilder; import me.chanjar.weixin.mp.util.http.apache.ApacheMaterialDeleteRequestExecutor; import me.chanjar.weixin.mp.util.http.jodd.JoddMaterialDeleteRequestExecutor; import me.chanjar.weixin.mp.util.http.okhttp.OkhttpMaterialDeleteRequestExecutor; -import okhttp3.*; - -import org.apache.http.HttpHost; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -public abstract class MaterialDeleteRequestExecutor implements RequestExecutor { - protected RequestHttp requestHttp; +public abstract class MaterialDeleteRequestExecutor implements RequestExecutor { + protected RequestHttp requestHttp; - public MaterialDeleteRequestExecutor(RequestHttp requestHttp){ - this.requestHttp =requestHttp; + public MaterialDeleteRequestExecutor(RequestHttp requestHttp) { + this.requestHttp = requestHttp; } - public static RequestExecutor create(RequestHttp requestHttp){ - switch (requestHttp.getRequestType()){ + public static RequestExecutor create(RequestHttp requestHttp) { + switch (requestHttp.getRequestType()) { case apacheHttp: return new ApacheMaterialDeleteRequestExecutor(requestHttp); case joddHttp: diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialNewsInfoRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialNewsInfoRequestExecutor.java index 92188b2a..0544fbe9 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialNewsInfoRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialNewsInfoRequestExecutor.java @@ -1,45 +1,21 @@ package me.chanjar.weixin.mp.util.http; -import jodd.http.HttpConnectionProvider; -import jodd.http.HttpRequest; -import jodd.http.HttpResponse; -import jodd.http.ProxyInfo; -import me.chanjar.weixin.common.bean.result.WxError; -import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.common.util.http.RequestExecutor; import me.chanjar.weixin.common.util.http.RequestHttp; -import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; - -import me.chanjar.weixin.common.util.http.okhttp.OkhttpProxyInfo; - -import me.chanjar.weixin.common.util.json.WxGsonBuilder; import me.chanjar.weixin.mp.bean.material.WxMpMaterialNews; import me.chanjar.weixin.mp.util.http.apache.ApacheMaterialNewsInfoRequestExecutor; import me.chanjar.weixin.mp.util.http.jodd.JoddMaterialNewsInfoRequestExecutor; import me.chanjar.weixin.mp.util.http.okhttp.OkhttpMaterialNewsInfoRequestExecutor; -import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; -import okhttp3.*; - -import org.apache.http.HttpHost; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -public abstract class MaterialNewsInfoRequestExecutor implements RequestExecutor { - protected RequestHttp requestHttp; +public abstract class MaterialNewsInfoRequestExecutor implements RequestExecutor { + protected RequestHttp requestHttp; - public MaterialNewsInfoRequestExecutor(RequestHttp requestHttp){ - this.requestHttp =requestHttp; + public MaterialNewsInfoRequestExecutor(RequestHttp requestHttp) { + this.requestHttp = requestHttp; } - public static RequestExecutor create(RequestHttp requestHttp){ - switch (requestHttp.getRequestType()){ + public static RequestExecutor create(RequestHttp requestHttp) { + switch (requestHttp.getRequestType()) { case apacheHttp: return new ApacheMaterialNewsInfoRequestExecutor(requestHttp); case joddHttp: diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialUploadRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialUploadRequestExecutor.java index 54d1d0e7..c44b5f16 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialUploadRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialUploadRequestExecutor.java @@ -1,47 +1,22 @@ package me.chanjar.weixin.mp.util.http; -import jodd.http.HttpConnectionProvider; -import jodd.http.HttpRequest; -import jodd.http.HttpResponse; -import jodd.http.ProxyInfo; -import me.chanjar.weixin.common.bean.result.WxError; -import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.common.util.http.RequestExecutor; import me.chanjar.weixin.common.util.http.RequestHttp; -import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; - -import me.chanjar.weixin.common.util.http.okhttp.OkhttpProxyInfo; - -import me.chanjar.weixin.common.util.json.WxGsonBuilder; import me.chanjar.weixin.mp.bean.material.WxMpMaterial; import me.chanjar.weixin.mp.bean.material.WxMpMaterialUploadResult; import me.chanjar.weixin.mp.util.http.apache.ApacheMaterialUploadRequestExecutor; import me.chanjar.weixin.mp.util.http.jodd.JoddMaterialUploadRequestExecutor; import me.chanjar.weixin.mp.util.http.okhttp.OkhttpMaterialUploadRequestExecutor; -import okhttp3.*; - -import org.apache.http.HttpHost; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.mime.HttpMultipartMode; -import org.apache.http.entity.mime.MultipartEntityBuilder; -import org.apache.http.impl.client.CloseableHttpClient; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.Map; +public abstract class MaterialUploadRequestExecutor implements RequestExecutor { + protected RequestHttp requestHttp; -public abstract class MaterialUploadRequestExecutor implements RequestExecutor { - protected RequestHttp requestHttp; - public MaterialUploadRequestExecutor(RequestHttp requestHttp){ - this.requestHttp =requestHttp; + public MaterialUploadRequestExecutor(RequestHttp requestHttp) { + this.requestHttp = requestHttp; } - public static RequestExecutor create(RequestHttp requestHttp){ - switch (requestHttp.getRequestType()){ + public static RequestExecutor create(RequestHttp requestHttp) { + switch (requestHttp.getRequestType()) { case apacheHttp: return new ApacheMaterialUploadRequestExecutor(requestHttp); case joddHttp: diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialVideoInfoRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialVideoInfoRequestExecutor.java index c042d261..285e05c4 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialVideoInfoRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialVideoInfoRequestExecutor.java @@ -1,43 +1,21 @@ package me.chanjar.weixin.mp.util.http; -import jodd.http.HttpConnectionProvider; -import jodd.http.HttpRequest; -import jodd.http.HttpResponse; -import jodd.http.ProxyInfo; -import me.chanjar.weixin.common.bean.result.WxError; -import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.common.util.http.RequestExecutor; import me.chanjar.weixin.common.util.http.RequestHttp; -import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; - -import me.chanjar.weixin.common.util.http.okhttp.OkhttpProxyInfo; - -import me.chanjar.weixin.common.util.json.WxGsonBuilder; import me.chanjar.weixin.mp.bean.material.WxMpMaterialVideoInfoResult; import me.chanjar.weixin.mp.util.http.apache.ApacheMaterialVideoInfoRequestExecutor; import me.chanjar.weixin.mp.util.http.jodd.JoddMaterialVideoInfoRequestExecutor; import me.chanjar.weixin.mp.util.http.okhttp.OkhttpMaterialVideoInfoRequestExecutor; -import okhttp3.*; - -import org.apache.http.HttpHost; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; +public abstract class MaterialVideoInfoRequestExecutor implements RequestExecutor { + protected RequestHttp requestHttp; -public abstract class MaterialVideoInfoRequestExecutor implements RequestExecutor { - protected RequestHttp requestHttp; - public MaterialVideoInfoRequestExecutor(RequestHttp requestHttp){ - this.requestHttp =requestHttp; + public MaterialVideoInfoRequestExecutor(RequestHttp requestHttp) { + this.requestHttp = requestHttp; } - public static RequestExecutor create(RequestHttp requestHttp){ - switch (requestHttp.getRequestType()){ + public static RequestExecutor create(RequestHttp requestHttp) { + switch (requestHttp.getRequestType()) { case apacheHttp: return new ApacheMaterialVideoInfoRequestExecutor(requestHttp); case joddHttp: diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialVoiceAndImageDownloadRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialVoiceAndImageDownloadRequestExecutor.java index 75255346..7c47532a 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialVoiceAndImageDownloadRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialVoiceAndImageDownloadRequestExecutor.java @@ -1,36 +1,13 @@ package me.chanjar.weixin.mp.util.http; -import jodd.http.HttpConnectionProvider; -import jodd.http.HttpRequest; -import jodd.http.HttpResponse; -import jodd.http.ProxyInfo; -import me.chanjar.weixin.common.bean.result.WxError; -import me.chanjar.weixin.common.exception.WxErrorException; - import me.chanjar.weixin.common.util.http.RequestExecutor; import me.chanjar.weixin.common.util.http.RequestHttp; -import me.chanjar.weixin.common.util.http.apache.InputStreamResponseHandler; -import me.chanjar.weixin.common.util.http.okhttp.OkhttpProxyInfo; -import me.chanjar.weixin.common.util.json.WxGsonBuilder; import me.chanjar.weixin.mp.util.http.apache.ApacheMaterialVoiceAndImageDownloadRequestExecutor; import me.chanjar.weixin.mp.util.http.jodd.JoddMaterialVoiceAndImageDownloadRequestExecutor; import me.chanjar.weixin.mp.util.http.okhttp.OkhttpMaterialVoiceAndImageDownloadRequestExecutor; -import okhttp3.*; - -import org.apache.commons.io.IOUtils; -import org.apache.http.HttpHost; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import java.io.ByteArrayInputStream; import java.io.File; -import java.io.IOException; import java.io.InputStream; -import java.util.HashMap; -import java.util.Map; public abstract class MaterialVoiceAndImageDownloadRequestExecutor implements RequestExecutor { protected RequestHttp requestHttp; diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MediaImgUploadRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MediaImgUploadRequestExecutor.java index f4713afd..dc5e037b 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MediaImgUploadRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MediaImgUploadRequestExecutor.java @@ -1,48 +1,26 @@ package me.chanjar.weixin.mp.util.http; -import jodd.http.HttpConnectionProvider; -import jodd.http.HttpRequest; -import jodd.http.HttpResponse; -import jodd.http.ProxyInfo; - -import me.chanjar.weixin.common.bean.result.WxError; -import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.common.util.http.RequestExecutor; import me.chanjar.weixin.common.util.http.RequestHttp; -import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; - -import me.chanjar.weixin.common.util.http.okhttp.OkhttpProxyInfo; - import me.chanjar.weixin.mp.bean.material.WxMediaImgUploadResult; import me.chanjar.weixin.mp.util.http.apache.ApacheMediaImgUploadRequestExecutor; import me.chanjar.weixin.mp.util.http.jodd.JoddMediaImgUploadRequestExecutor; import me.chanjar.weixin.mp.util.http.okhttp.OkhttpMediaImgUploadRequestExecutor; -import okhttp3.*; - -import org.apache.http.HttpEntity; -import org.apache.http.HttpHost; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.mime.HttpMultipartMode; -import org.apache.http.entity.mime.MultipartEntityBuilder; -import org.apache.http.impl.client.CloseableHttpClient; import java.io.File; -import java.io.IOException; /** * @author miller */ -public abstract class MediaImgUploadRequestExecutor implements RequestExecutor { - protected RequestHttp requestHttp; - public MediaImgUploadRequestExecutor(RequestHttp requestHttp){ - this.requestHttp =requestHttp; +public abstract class MediaImgUploadRequestExecutor implements RequestExecutor { + protected RequestHttp requestHttp; + + public MediaImgUploadRequestExecutor(RequestHttp requestHttp) { + this.requestHttp = requestHttp; } - public static RequestExecutor create(RequestHttp requestHttp){ - switch (requestHttp.getRequestType()){ + public static RequestExecutor create(RequestHttp requestHttp) { + switch (requestHttp.getRequestType()) { case apacheHttp: return new ApacheMediaImgUploadRequestExecutor(requestHttp); case joddHttp: diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/QrCodeRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/QrCodeRequestExecutor.java index 151a20e4..3fc34d87 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/QrCodeRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/QrCodeRequestExecutor.java @@ -1,55 +1,28 @@ package me.chanjar.weixin.mp.util.http; -import jodd.http.HttpConnectionProvider; -import jodd.http.HttpRequest; -import jodd.http.HttpResponse; -import jodd.http.ProxyInfo; -import jodd.util.MimeTypes; -import me.chanjar.weixin.common.bean.result.WxError; -import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.common.util.fs.FileUtils; - import me.chanjar.weixin.common.util.http.RequestExecutor; import me.chanjar.weixin.common.util.http.RequestHttp; -import me.chanjar.weixin.common.util.http.apache.InputStreamResponseHandler; -import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; -import me.chanjar.weixin.common.util.http.okhttp.OkhttpProxyInfo; - import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket; import me.chanjar.weixin.mp.util.http.apache.ApacheQrCodeRequestExecutor; import me.chanjar.weixin.mp.util.http.jodd.JoddQrCodeRequestExecutor; import me.chanjar.weixin.mp.util.http.okhttp.OkhttpQrCodeRequestExecutor; -import okhttp3.*; - -import org.apache.http.Header; -import org.apache.http.HttpHost; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.entity.ContentType; -import org.apache.http.impl.client.CloseableHttpClient; -import java.io.ByteArrayInputStream; import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.URLEncoder; -import java.util.UUID; /** * 获得QrCode图片 请求执行器 * * @author chanjarster */ -public abstract class QrCodeRequestExecutor implements RequestExecutor { +public abstract class QrCodeRequestExecutor implements RequestExecutor { protected RequestHttp requestHttp; - public QrCodeRequestExecutor(RequestHttp requestHttp){ - this.requestHttp =requestHttp; + public QrCodeRequestExecutor(RequestHttp requestHttp) { + this.requestHttp = requestHttp; } - public static RequestExecutor create(RequestHttp requestHttp){ - switch (requestHttp.getRequestType()){ + public static RequestExecutor create(RequestHttp requestHttp) { + switch (requestHttp.getRequestType()) { case apacheHttp: return new ApacheQrCodeRequestExecutor(requestHttp); case joddHttp: diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialDeleteRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialDeleteRequestExecutor.java index 5446483f..be0991d3 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialDeleteRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialDeleteRequestExecutor.java @@ -1,9 +1,11 @@ package me.chanjar.weixin.mp.util.http.apache; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.RequestHttp; +import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; +import me.chanjar.weixin.common.util.json.WxGsonBuilder; +import me.chanjar.weixin.mp.util.http.MaterialDeleteRequestExecutor; import org.apache.http.HttpHost; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; @@ -11,17 +13,14 @@ import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; -import me.chanjar.weixin.common.bean.result.WxError; -import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.common.util.http.RequestHttp; -import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; -import me.chanjar.weixin.common.util.json.WxGsonBuilder; -import me.chanjar.weixin.mp.util.http.MaterialDeleteRequestExecutor; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; /** * Created by ecoolper on 2017/5/5. */ -public class ApacheMaterialDeleteRequestExecutor extends MaterialDeleteRequestExecutor { +public class ApacheMaterialDeleteRequestExecutor extends MaterialDeleteRequestExecutor { public ApacheMaterialDeleteRequestExecutor(RequestHttp requestHttp) { super(requestHttp); } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialNewsInfoRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialNewsInfoRequestExecutor.java index 81fb8019..77d22659 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialNewsInfoRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialNewsInfoRequestExecutor.java @@ -1,16 +1,5 @@ package me.chanjar.weixin.mp.util.http.apache; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -import org.apache.http.HttpHost; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; - import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.common.util.http.RequestHttp; @@ -19,11 +8,21 @@ import me.chanjar.weixin.common.util.json.WxGsonBuilder; import me.chanjar.weixin.mp.bean.material.WxMpMaterialNews; import me.chanjar.weixin.mp.util.http.MaterialNewsInfoRequestExecutor; import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; +import org.apache.http.HttpHost; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; /** * Created by ecoolper on 2017/5/5. */ -public class ApacheMaterialNewsInfoRequestExecutor extends MaterialNewsInfoRequestExecutor { +public class ApacheMaterialNewsInfoRequestExecutor extends MaterialNewsInfoRequestExecutor { public ApacheMaterialNewsInfoRequestExecutor(RequestHttp requestHttp) { super(requestHttp); } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialUploadRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialUploadRequestExecutor.java index af6ab10a..474fcb99 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialUploadRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialUploadRequestExecutor.java @@ -1,10 +1,13 @@ package me.chanjar.weixin.mp.util.http.apache; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.Map; - +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.RequestHttp; +import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; +import me.chanjar.weixin.common.util.json.WxGsonBuilder; +import me.chanjar.weixin.mp.bean.material.WxMpMaterial; +import me.chanjar.weixin.mp.bean.material.WxMpMaterialUploadResult; +import me.chanjar.weixin.mp.util.http.MaterialUploadRequestExecutor; import org.apache.http.HttpHost; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; @@ -14,19 +17,15 @@ import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; -import me.chanjar.weixin.common.bean.result.WxError; -import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.common.util.http.RequestHttp; -import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; -import me.chanjar.weixin.common.util.json.WxGsonBuilder; -import me.chanjar.weixin.mp.bean.material.WxMpMaterial; -import me.chanjar.weixin.mp.bean.material.WxMpMaterialUploadResult; -import me.chanjar.weixin.mp.util.http.MaterialUploadRequestExecutor; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.Map; /** * Created by ecoolper on 2017/5/5. */ -public class ApacheMaterialUploadRequestExecutor extends MaterialUploadRequestExecutor { +public class ApacheMaterialUploadRequestExecutor extends MaterialUploadRequestExecutor { public ApacheMaterialUploadRequestExecutor(RequestHttp requestHttp) { super(requestHttp); } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialVideoInfoRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialVideoInfoRequestExecutor.java index 1d1e2c57..7b81ea86 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialVideoInfoRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialVideoInfoRequestExecutor.java @@ -1,16 +1,5 @@ package me.chanjar.weixin.mp.util.http.apache; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -import org.apache.http.HttpHost; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; - import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.common.util.http.RequestHttp; @@ -18,11 +7,21 @@ import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; import me.chanjar.weixin.common.util.json.WxGsonBuilder; import me.chanjar.weixin.mp.bean.material.WxMpMaterialVideoInfoResult; import me.chanjar.weixin.mp.util.http.MaterialVideoInfoRequestExecutor; +import org.apache.http.HttpHost; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; /** * Created by ecoolper on 2017/5/5. */ -public class ApacheMaterialVideoInfoRequestExecutor extends MaterialVideoInfoRequestExecutor { +public class ApacheMaterialVideoInfoRequestExecutor extends MaterialVideoInfoRequestExecutor { public ApacheMaterialVideoInfoRequestExecutor(RequestHttp requestHttp) { super(requestHttp); } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialVoiceAndImageDownloadRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialVoiceAndImageDownloadRequestExecutor.java index 92cf1c5a..87d7b545 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialVoiceAndImageDownloadRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMaterialVoiceAndImageDownloadRequestExecutor.java @@ -1,12 +1,11 @@ package me.chanjar.weixin.mp.util.http.apache; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; -import java.util.Map; - +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.RequestHttp; +import me.chanjar.weixin.common.util.http.apache.InputStreamResponseHandler; +import me.chanjar.weixin.common.util.json.WxGsonBuilder; +import me.chanjar.weixin.mp.util.http.MaterialVoiceAndImageDownloadRequestExecutor; import org.apache.commons.io.IOUtils; import org.apache.http.HttpHost; import org.apache.http.client.config.RequestConfig; @@ -15,17 +14,17 @@ import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; -import me.chanjar.weixin.common.bean.result.WxError; -import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.common.util.http.RequestHttp; -import me.chanjar.weixin.common.util.http.apache.InputStreamResponseHandler; -import me.chanjar.weixin.common.util.json.WxGsonBuilder; -import me.chanjar.weixin.mp.util.http.MaterialVoiceAndImageDownloadRequestExecutor; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; /** * Created by ecoolper on 2017/5/5. */ -public class ApacheMaterialVoiceAndImageDownloadRequestExecutor extends MaterialVoiceAndImageDownloadRequestExecutor { +public class ApacheMaterialVoiceAndImageDownloadRequestExecutor extends MaterialVoiceAndImageDownloadRequestExecutor { public ApacheMaterialVoiceAndImageDownloadRequestExecutor(RequestHttp requestHttp, File tmpDirFile) { super(requestHttp, tmpDirFile); } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMediaImgUploadRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMediaImgUploadRequestExecutor.java index 4aaf2f12..63e278e4 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMediaImgUploadRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheMediaImgUploadRequestExecutor.java @@ -1,8 +1,11 @@ package me.chanjar.weixin.mp.util.http.apache; -import java.io.File; -import java.io.IOException; - +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.RequestHttp; +import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; +import me.chanjar.weixin.mp.bean.material.WxMediaImgUploadResult; +import me.chanjar.weixin.mp.util.http.MediaImgUploadRequestExecutor; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.client.config.RequestConfig; @@ -13,17 +16,13 @@ import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; -import me.chanjar.weixin.common.bean.result.WxError; -import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.common.util.http.RequestHttp; -import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; -import me.chanjar.weixin.mp.bean.material.WxMediaImgUploadResult; -import me.chanjar.weixin.mp.util.http.MediaImgUploadRequestExecutor; +import java.io.File; +import java.io.IOException; /** * Created by ecoolper on 2017/5/5. */ -public class ApacheMediaImgUploadRequestExecutor extends MediaImgUploadRequestExecutor { +public class ApacheMediaImgUploadRequestExecutor extends MediaImgUploadRequestExecutor { public ApacheMediaImgUploadRequestExecutor(RequestHttp requestHttp) { super(requestHttp); } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheQrCodeRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheQrCodeRequestExecutor.java index dd84f293..d7bfe637 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheQrCodeRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/apache/ApacheQrCodeRequestExecutor.java @@ -1,19 +1,5 @@ package me.chanjar.weixin.mp.util.http.apache; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.URLEncoder; -import java.util.UUID; - -import org.apache.http.Header; -import org.apache.http.HttpHost; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.entity.ContentType; -import org.apache.http.impl.client.CloseableHttpClient; - import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.common.util.fs.FileUtils; @@ -22,11 +8,24 @@ import me.chanjar.weixin.common.util.http.apache.InputStreamResponseHandler; import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket; import me.chanjar.weixin.mp.util.http.QrCodeRequestExecutor; +import org.apache.http.Header; +import org.apache.http.HttpHost; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.entity.ContentType; +import org.apache.http.impl.client.CloseableHttpClient; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.URLEncoder; +import java.util.UUID; /** * Created by ecoolper on 2017/5/5. */ -public class ApacheQrCodeRequestExecutor extends QrCodeRequestExecutor { +public class ApacheQrCodeRequestExecutor extends QrCodeRequestExecutor { public ApacheQrCodeRequestExecutor(RequestHttp requestHttp) { super(requestHttp); } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpTemplateMessageGsonAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpTemplateMessageGsonAdapter.java index d6e0ff1d..9668a768 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpTemplateMessageGsonAdapter.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpTemplateMessageGsonAdapter.java @@ -28,7 +28,7 @@ public class WxMpTemplateMessageGsonAdapter implements JsonSerializer clz) { XStream xstream = XStreamInitializer.getInstance(); xstream.processAnnotations(clz); xstream.processAnnotations(getInnerClasses(clz)); - if(clz.equals(WxMpXmlMessage.class)){ + if (clz.equals(WxMpXmlMessage.class)) { // 操蛋的微信,模板消息推送成功的消息是MsgID,其他消息推送过来是MsgId xstream.aliasField("MsgID", WxMpXmlMessage.class, "msgId"); } diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxMpBusyRetryTest.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxMpBusyRetryTest.java index 8a8c7170..cc4dcf96 100644 --- a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxMpBusyRetryTest.java +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxMpBusyRetryTest.java @@ -3,11 +3,8 @@ package me.chanjar.weixin.mp.api; import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.common.util.http.RequestExecutor; - import me.chanjar.weixin.mp.api.impl.apache.WxMpServiceImpl; - -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.testng.annotations.*; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/test/ApiTestModule.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/test/ApiTestModule.java index 03e01444..2cfaec54 100644 --- a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/test/ApiTestModule.java +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/test/ApiTestModule.java @@ -6,7 +6,6 @@ import com.thoughtworks.xstream.XStream; import me.chanjar.weixin.common.util.xml.XStreamInitializer; import me.chanjar.weixin.mp.api.WxMpConfigStorage; import me.chanjar.weixin.mp.api.WxMpService; - import me.chanjar.weixin.mp.api.impl.apache.WxMpServiceImpl; import java.io.IOException; diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/WxMpDemoServer.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/WxMpDemoServer.java index 66b90d0f..e2c75f83 100644 --- a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/WxMpDemoServer.java +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/WxMpDemoServer.java @@ -6,7 +6,6 @@ import me.chanjar.weixin.mp.api.WxMpMessageHandler; import me.chanjar.weixin.mp.api.WxMpMessageRouter; import me.chanjar.weixin.mp.api.WxMpService; import me.chanjar.weixin.mp.api.impl.apache.WxMpServiceImpl; - import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletHandler; import org.eclipse.jetty.servlet.ServletHolder; diff --git a/weixin-java-mp/src/test/resources/logback-test.xml b/weixin-java-mp/src/test/resources/logback-test.xml index ed595101..9be51c9a 100644 --- a/weixin-java-mp/src/test/resources/logback-test.xml +++ b/weixin-java-mp/src/test/resources/logback-test.xml @@ -9,8 +9,8 @@ - + - + diff --git a/weixin-java-mp/src/test/resources/testng.xml b/weixin-java-mp/src/test/resources/testng.xml index a358cf1c..d8646355 100644 --- a/weixin-java-mp/src/test/resources/testng.xml +++ b/weixin-java-mp/src/test/resources/testng.xml @@ -1,30 +1,30 @@ - - - - - - - - - - - - - + + + + + + + + + + + + + - - - - - - - - - - - - + + + + + + + + + + + + diff --git a/weixin-java-osgi/pom.xml b/weixin-java-osgi/pom.xml index b44ef85d..43874695 100644 --- a/weixin-java-osgi/pom.xml +++ b/weixin-java-osgi/pom.xml @@ -1,6 +1,6 @@ - 4.0.0 @@ -119,7 +119,8 @@ ,org.joda.time.format;version="[1.6,2)";resolution:=optional ,org.kxml2.io;resolution:=optional ,org.w3c.dom;resolution:=optional - ,* + ,* + diff --git a/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/bean/WxPayOrderNotifyResponse.java b/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/bean/WxPayOrderNotifyResponse.java index 9d960c08..e3692931 100644 --- a/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/bean/WxPayOrderNotifyResponse.java +++ b/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/bean/WxPayOrderNotifyResponse.java @@ -4,7 +4,6 @@ import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamConverter; import com.thoughtworks.xstream.annotations.XStreamOmitField; - import me.chanjar.weixin.common.util.xml.XStreamCDataConverter; import me.chanjar.weixin.common.util.xml.XStreamInitializer; diff --git a/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/bean/request/WxPayBaseRequest.java b/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/bean/request/WxPayBaseRequest.java index 4d5cbbaa..65f10f5c 100644 --- a/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/bean/request/WxPayBaseRequest.java +++ b/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/bean/request/WxPayBaseRequest.java @@ -28,22 +28,6 @@ import java.math.BigDecimal; * @author binarywang(Binary Wang) */ public abstract class WxPayBaseRequest { - /** - * 检查请求参数内容,包括必填参数以及特殊约束 - */ - protected void checkFields() throws WxErrorException { - //check required fields - BeanUtils.checkRequiredFields(this); - - //check other parameters - this.checkConstraints(); - } - - /** - * 检查约束情况 - */ - protected abstract void checkConstraints(); - /** *

        * 公众账号ID
    @@ -68,7 +52,6 @@ public abstract class WxPayBaseRequest {
        */
       @XStreamAlias("mch_id")
       protected String mchId;
    -
       /**
        * 
        * 服务商模式下的子商户公众账号ID
    @@ -81,7 +64,6 @@ public abstract class WxPayBaseRequest {
        */
       @XStreamAlias("sub_appid")
       protected String subAppId;
    -
       /**
        * 
        * 服务商模式下的子商户号
    @@ -128,6 +110,22 @@ public abstract class WxPayBaseRequest {
         return new BigDecimal(yuan).setScale(2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).intValue();
       }
     
    +  /**
    +   * 检查请求参数内容,包括必填参数以及特殊约束
    +   */
    +  protected void checkFields() throws WxErrorException {
    +    //check required fields
    +    BeanUtils.checkRequiredFields(this);
    +
    +    //check other parameters
    +    this.checkConstraints();
    +  }
    +
    +  /**
    +   * 检查约束情况
    +   */
    +  protected abstract void checkConstraints();
    +
       public String getAppid() {
         return this.appid;
       }
    @@ -209,6 +207,7 @@ public abstract class WxPayBaseRequest {
        * 2、补充系统参数,如果未传入则从配置里读取
        * 3、生成签名,并设置进去
        * 
    + * * @param config 支付配置对象,用于读取相应系统配置信息 */ public void checkAndSign(WxPayConfig config) throws WxErrorException { @@ -227,7 +226,7 @@ public abstract class WxPayBaseRequest { } if (StringUtils.isBlank(getSubMchId())) { - this. setSubMchId(config.getSubMchId()); + this.setSubMchId(config.getSubMchId()); } if (StringUtils.isBlank(getNonceStr())) { diff --git a/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/bean/request/WxPayRefundRequest.java b/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/bean/request/WxPayRefundRequest.java index c7fc8c26..8d80148c 100644 --- a/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/bean/request/WxPayRefundRequest.java +++ b/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/bean/request/WxPayRefundRequest.java @@ -28,16 +28,6 @@ import java.util.Arrays; public class WxPayRefundRequest extends WxPayBaseRequest { private static final String[] REFUND_ACCOUNT = new String[]{"REFUND_SOURCE_RECHARGE_FUNDS", "REFUND_SOURCE_UNSETTLED_FUNDS"}; - - @Override - public void checkAndSign(WxPayConfig config) throws WxErrorException { - if (StringUtils.isBlank(this.getOpUserId())) { - this.setOpUserId(config.getMchId()); - } - - super.checkAndSign(config); - } - /** *
        * 设备号
    @@ -50,7 +40,6 @@ public class WxPayRefundRequest extends WxPayBaseRequest {
        */
       @XStreamAlias("device_info")
       private String deviceInfo;
    -
       /**
        * 
        * 微信订单号
    @@ -63,7 +52,6 @@ public class WxPayRefundRequest extends WxPayBaseRequest {
        */
       @XStreamAlias("transaction_id")
       private String transactionId;
    -
       /**
        * 
        * 商户订单号
    @@ -76,7 +64,6 @@ public class WxPayRefundRequest extends WxPayBaseRequest {
        */
       @XStreamAlias("out_trade_no")
       private String outTradeNo;
    -
       /**
        * 
        * 商户退款单号
    @@ -90,7 +77,6 @@ public class WxPayRefundRequest extends WxPayBaseRequest {
       @Required
       @XStreamAlias("out_refund_no")
       private String outRefundNo;
    -
       /**
        * 
        * 订单金额
    @@ -104,7 +90,6 @@ public class WxPayRefundRequest extends WxPayBaseRequest {
       @Required
       @XStreamAlias("total_fee")
       private Integer totalFee;
    -
       /**
        * 
        * 退款金额
    @@ -118,7 +103,6 @@ public class WxPayRefundRequest extends WxPayBaseRequest {
       @Required
       @XStreamAlias("refund_fee")
       private Integer refundFee;
    -
       /**
        * 
        * 货币种类
    @@ -131,7 +115,6 @@ public class WxPayRefundRequest extends WxPayBaseRequest {
        */
       @XStreamAlias("refund_fee_type")
       private String refundFeeType;
    -
       /**
        * 
        * 操作员
    @@ -145,7 +128,6 @@ public class WxPayRefundRequest extends WxPayBaseRequest {
       //@Required
       @XStreamAlias("op_user_id")
       private String opUserId;
    -
       /**
        * 
        * 退款资金来源
    @@ -186,6 +168,15 @@ public class WxPayRefundRequest extends WxPayBaseRequest {
         return new Builder();
       }
     
    +  @Override
    +  public void checkAndSign(WxPayConfig config) throws WxErrorException {
    +    if (StringUtils.isBlank(this.getOpUserId())) {
    +      this.setOpUserId(config.getMchId());
    +    }
    +
    +    super.checkAndSign(config);
    +  }
    +
       public String getDeviceInfo() {
         return this.deviceInfo;
       }
    diff --git a/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/bean/request/WxPayShorturlRequest.java b/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/bean/request/WxPayShorturlRequest.java
    index 849d9283..714e07ea 100644
    --- a/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/bean/request/WxPayShorturlRequest.java
    +++ b/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/bean/request/WxPayShorturlRequest.java
    @@ -24,18 +24,18 @@ public class WxPayShorturlRequest extends WxPayBaseRequest {
       @XStreamAlias("long_url")
       private String longUrl;
     
    -  public String getLongUrl() {
    -    return this.longUrl;
    +  public WxPayShorturlRequest() {
       }
     
    -  public void setLongUrl(String longUrl) {
    +  public WxPayShorturlRequest(String longUrl) {
         this.longUrl = longUrl;
       }
     
    -  public WxPayShorturlRequest() {
    +  public String getLongUrl() {
    +    return this.longUrl;
       }
     
    -  public WxPayShorturlRequest(String longUrl) {
    +  public void setLongUrl(String longUrl) {
         this.longUrl = longUrl;
       }
     
    diff --git a/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/bean/result/WxScanPayNotifyResult.java b/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/bean/result/WxScanPayNotifyResult.java
    index 5bf11068..cdb94a9b 100644
    --- a/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/bean/result/WxScanPayNotifyResult.java
    +++ b/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/bean/result/WxScanPayNotifyResult.java
    @@ -1,24 +1,24 @@
    -package com.github.binarywang.wxpay.bean.result;
    -
    -import java.io.Serializable;
    -
    -import com.thoughtworks.xstream.annotations.XStreamAlias;
    -
    -public class WxScanPayNotifyResult  extends WxPayBaseResult implements Serializable{
    -  private static final long serialVersionUID = 3381324564266118986L;
    -  
    -  /**
    -   * 预支付ID
    -   */
    -  @XStreamAlias("prepay_id")
    -  private String prepayId;
    -
    -  public String getPrepayId() {
    -    return prepayId;
    -  }
    -
    -  public void setPrepayId(String prepayId) {
    -    this.prepayId = prepayId;
    -  }
    -  
    -}
    +package com.github.binarywang.wxpay.bean.result;
    +
    +import com.thoughtworks.xstream.annotations.XStreamAlias;
    +
    +import java.io.Serializable;
    +
    +public class WxScanPayNotifyResult extends WxPayBaseResult implements Serializable {
    +  private static final long serialVersionUID = 3381324564266118986L;
    +
    +  /**
    +   * 预支付ID
    +   */
    +  @XStreamAlias("prepay_id")
    +  private String prepayId;
    +
    +  public String getPrepayId() {
    +    return prepayId;
    +  }
    +
    +  public void setPrepayId(String prepayId) {
    +    this.prepayId = prepayId;
    +  }
    +
    +}
    diff --git a/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/config/WxPayConfig.java b/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/config/WxPayConfig.java
    index c05cd7e7..838b5791 100644
    --- a/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/config/WxPayConfig.java
    +++ b/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/config/WxPayConfig.java
    @@ -24,50 +24,19 @@ public class WxPayConfig {
       private String keyPath;
       private boolean useSandboxEnv = false;
     
    -  public void setNotifyUrl(String notifyUrl) {
    -    this.notifyUrl = notifyUrl;
    -  }
    -
    -  public void setTradeType(String tradeType) {
    -    this.tradeType = tradeType;
    +  public String getKeyPath() {
    +    return keyPath;
       }
     
       /**
        * 设置证书
    +   *
        * @param keyPath apiclient_cert.p12的文件的绝对路径
        */
       public void setKeyPath(String keyPath) {
         this.keyPath = keyPath;
       }
     
    -  public String getKeyPath() {
    -    return keyPath;
    -  }
    -
    -  public void setAppId(String appId) {
    -    this.appId = appId;
    -  }
    -
    -  public void setSubAppId(String subAppId) {
    -    this.subAppId = subAppId;
    -  }
    -
    -  public void setMchId(String mchId) {
    -    this.mchId = mchId;
    -  }
    -
    -  public void setMchKey(String mchKey) {
    -    this.mchKey = mchKey;
    -  }
    -
    -  public void setSubMchId(String subMchId) {
    -    this.subMchId = subMchId;
    -  }
    -
    -  public void setSslContext(SSLContext sslContext) {
    -    this.sslContext = sslContext;
    -  }
    -
       /**
        * 商户号
        */
    @@ -75,6 +44,10 @@ public class WxPayConfig {
         return this.mchId;
       }
     
    +  public void setMchId(String mchId) {
    +    this.mchId = mchId;
    +  }
    +
       /**
        * 商户密钥
        */
    @@ -82,6 +55,10 @@ public class WxPayConfig {
         return this.mchKey;
       }
     
    +  public void setMchKey(String mchKey) {
    +    this.mchKey = mchKey;
    +  }
    +
       /**
        * 公众号appid
        */
    @@ -89,6 +66,10 @@ public class WxPayConfig {
         return this.appId;
       }
     
    +  public void setAppId(String appId) {
    +    this.appId = appId;
    +  }
    +
       /**
        * 服务商模式下的子商户公众账号ID
        */
    @@ -96,6 +77,10 @@ public class WxPayConfig {
         return this.subAppId;
       }
     
    +  public void setSubAppId(String subAppId) {
    +    this.subAppId = subAppId;
    +  }
    +
       /**
        * 服务商模式下的子商户号
        */
    @@ -103,6 +88,10 @@ public class WxPayConfig {
         return this.subMchId;
       }
     
    +  public void setSubMchId(String subMchId) {
    +    this.subMchId = subMchId;
    +  }
    +
       /**
        * 微信支付异步回掉地址,通知url必须为直接可访问的url,不能携带参数。
        */
    @@ -110,6 +99,10 @@ public class WxPayConfig {
         return this.notifyUrl;
       }
     
    +  public void setNotifyUrl(String notifyUrl) {
    +    this.notifyUrl = notifyUrl;
    +  }
    +
       /**
        * 交易类型
        * 
    @@ -122,10 +115,18 @@ public class WxPayConfig {
         return this.tradeType;
       }
     
    +  public void setTradeType(String tradeType) {
    +    this.tradeType = tradeType;
    +  }
    +
       public SSLContext getSslContext() {
         return this.sslContext;
       }
     
    +  public void setSslContext(SSLContext sslContext) {
    +    this.sslContext = sslContext;
    +  }
    +
       /**
        * 微信支付是否使用仿真测试环境
        * 默认不使用
    diff --git a/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/service/WxPayService.java b/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/service/WxPayService.java
    index e336cd21..c04d7706 100644
    --- a/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/service/WxPayService.java
    +++ b/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/service/WxPayService.java
    @@ -288,6 +288,7 @@ public interface WxPayService {
        *  接口地址:https://api.mch.weixin.qq.com/tools/shorturl
        *  是否需要证书:否
        * 
    + * * @param request 请求对象 */ String shorturl(WxPayShorturlRequest request) throws WxErrorException; @@ -296,8 +297,9 @@ public interface WxPayService { *
        *  转换短链接
        * 
    - * @see WxPayService#shorturl(WxPayShorturlRequest) + * * @param longUrl 需要被压缩的网址 + * @see WxPayService#shorturl(WxPayShorturlRequest) */ String shorturl(String longUrl) throws WxErrorException; @@ -310,6 +312,7 @@ public interface WxPayService { * 接口链接: * https://api.mch.weixin.qq.com/tools/authcodetoopenid *
    + * * @param request 请求对象 * @return openid */ @@ -319,9 +322,10 @@ public interface WxPayService { *
        * 授权码查询OPENID接口
        * 
    - * @see WxPayService#authcode2Openid(WxPayAuthcode2OpenidRequest) + * * @param authCode 授权码 * @return openid + * @see WxPayService#authcode2Openid(WxPayAuthcode2OpenidRequest) */ String authcode2Openid(String authCode) throws WxErrorException; } diff --git a/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/service/impl/WxPayServiceImpl.java b/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/service/impl/WxPayServiceImpl.java index c15a3ab6..90778999 100644 --- a/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/service/impl/WxPayServiceImpl.java +++ b/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/service/impl/WxPayServiceImpl.java @@ -17,11 +17,11 @@ import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.net.ssl.SSLContext; import java.io.File; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map; -import javax.net.ssl.SSLContext; /** * Created by Binary Wang on 2016/7/28. diff --git a/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/util/SignUtils.java b/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/util/SignUtils.java index 2a6030f3..33e18c49 100644 --- a/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/util/SignUtils.java +++ b/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/util/SignUtils.java @@ -36,7 +36,7 @@ public class SignUtils { * @return 签名字符串 */ public static String createSign(Map params, String signKey) { -// if (this.getConfig().useSandboxForWxPay()) { +// if (this.getConfig().useSandbox()) { // //使用仿真测试环境 // //TODO 目前测试发现,以下两行代码都会出问题,所以暂不建议使用仿真测试环境 // signKey = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456"; @@ -49,11 +49,11 @@ public class SignUtils { for (String key : sortedMap.keySet()) { String value = params.get(key); if (StringUtils.isNotEmpty(value) && !"sign".equals(key) && !"key".equals(key)) { - toSign.append(key + "=" + value + "&"); + toSign.append(key).append("=").append(value).append("&"); } } - toSign.append("key=" + signKey); + toSign.append("key=").append(signKey); return DigestUtils.md5Hex(toSign.toString()).toUpperCase(); } diff --git a/weixin-java-pay/src/test/java/com/github/binarywang/wxpay/service/impl/WxPayServiceImplTest.java b/weixin-java-pay/src/test/java/com/github/binarywang/wxpay/service/impl/WxPayServiceImplTest.java index b59bd1eb..1ca8d2e6 100644 --- a/weixin-java-pay/src/test/java/com/github/binarywang/wxpay/service/impl/WxPayServiceImplTest.java +++ b/weixin-java-pay/src/test/java/com/github/binarywang/wxpay/service/impl/WxPayServiceImplTest.java @@ -1,7 +1,5 @@ package com.github.binarywang.wxpay.service.impl; -import static org.testng.Assert.*; - import com.github.binarywang.utils.qrcode.QrcodeUtils; import com.github.binarywang.wxpay.bean.request.*; import com.github.binarywang.wxpay.bean.result.*; @@ -12,14 +10,15 @@ import com.google.inject.Inject; import me.chanjar.weixin.common.exception.WxErrorException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.testng.annotations.Guice; -import org.testng.annotations.Test; +import org.testng.annotations.*; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.util.Map; +import static org.testng.Assert.*; + /** * 测试支付相关接口 * Created by Binary Wang on 2016/7/28. From 1806389a4dcadc27e17742760be0b467043b9954 Mon Sep 17 00:00:00 2001 From: Binary Wang Date: Thu, 11 May 2017 17:07:32 +0800 Subject: [PATCH 13/13] =?UTF-8?q?=E6=89=B9=E9=87=8F=E6=A0=BC=E5=BC=8F?= =?UTF-8?q?=E5=8C=96=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cp/api/impl/apache/WxCpServiceImpl.java | 1 - .../mp/api/impl/apache/WxMpServiceImpl.java | 21 ++--- .../mp/api/impl/jodd/WxMpServiceImpl.java | 7 +- .../kefu/request/WxMpKfAccountRequest.java | 88 +++++++++---------- .../JoddMaterialDeleteRequestExecutor.java | 6 +- .../JoddMaterialNewsInfoRequestExecutor.java | 6 +- .../JoddMaterialUploadRequestExecutor.java | 12 +-- .../JoddMaterialVideoInfoRequestExecutor.java | 6 +- ...lVoiceAndImageDownloadRequestExecutor.java | 16 ++-- .../JoddMediaImgUploadRequestExecutor.java | 8 +- .../http/jodd/JoddQrCodeRequestExecutor.java | 16 ++-- .../OkhttpMaterialDeleteRequestExecutor.java | 5 +- ...OkhttpMaterialNewsInfoRequestExecutor.java | 4 +- .../OkhttpMaterialUploadRequestExecutor.java | 20 ++--- ...khttpMaterialVideoInfoRequestExecutor.java | 6 +- ...lVoiceAndImageDownloadRequestExecutor.java | 13 ++- .../OkhttpMediaImgUploadRequestExecutor.java | 6 +- .../okhttp/OkhttpQrCodeRequestExecutor.java | 12 +-- 18 files changed, 115 insertions(+), 138 deletions(-) diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/impl/apache/WxCpServiceImpl.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/impl/apache/WxCpServiceImpl.java index 71ccbcd0..006bb52e 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/impl/apache/WxCpServiceImpl.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/impl/apache/WxCpServiceImpl.java @@ -8,7 +8,6 @@ import me.chanjar.weixin.common.util.http.HttpType; import me.chanjar.weixin.common.util.http.apache.ApacheHttpClientBuilder; import me.chanjar.weixin.common.util.http.apache.DefaultApacheHttpClientBuilder; import me.chanjar.weixin.cp.api.WxCpConfigStorage; - import me.chanjar.weixin.cp.api.impl.AbstractWxCpServiceImpl; import org.apache.http.HttpHost; import org.apache.http.client.config.RequestConfig; diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/apache/WxMpServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/apache/WxMpServiceImpl.java index d0991a5b..fdce402e 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/apache/WxMpServiceImpl.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/apache/WxMpServiceImpl.java @@ -1,24 +1,15 @@ package me.chanjar.weixin.mp.api.impl.apache; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; import me.chanjar.weixin.common.bean.WxAccessToken; -import me.chanjar.weixin.common.bean.WxJsapiSignature; import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.common.session.StandardSessionManager; -import me.chanjar.weixin.common.session.WxSessionManager; -import me.chanjar.weixin.common.util.RandomUtils; -import me.chanjar.weixin.common.util.crypto.SHA1; -import me.chanjar.weixin.common.util.http.*; +import me.chanjar.weixin.common.util.http.HttpType; +import me.chanjar.weixin.common.util.http.RequestHttp; import me.chanjar.weixin.common.util.http.apache.ApacheHttpClientBuilder; import me.chanjar.weixin.common.util.http.apache.DefaultApacheHttpClientBuilder; -import me.chanjar.weixin.mp.api.*; -import me.chanjar.weixin.mp.api.impl.*; -import me.chanjar.weixin.mp.bean.*; -import me.chanjar.weixin.mp.bean.result.*; +import me.chanjar.weixin.mp.api.WxMpConfigStorage; +import me.chanjar.weixin.mp.api.WxMpService; +import me.chanjar.weixin.mp.api.impl.AbstractWxMpServiceImpl; import org.apache.http.HttpHost; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; @@ -32,7 +23,7 @@ import java.util.concurrent.locks.Lock; /** * apache-http方式实现 */ -public class WxMpServiceImpl extends AbstractWxMpServiceImpl { +public class WxMpServiceImpl extends AbstractWxMpServiceImpl { private CloseableHttpClient httpClient; private HttpHost httpProxy; diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/jodd/WxMpServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/jodd/WxMpServiceImpl.java index b32ea3eb..6f02ff80 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/jodd/WxMpServiceImpl.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/jodd/WxMpServiceImpl.java @@ -7,15 +7,16 @@ import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.common.util.http.HttpType; import me.chanjar.weixin.common.util.http.RequestHttp; -import me.chanjar.weixin.mp.api.*; -import me.chanjar.weixin.mp.api.impl.*; +import me.chanjar.weixin.mp.api.WxMpConfigStorage; +import me.chanjar.weixin.mp.api.WxMpService; +import me.chanjar.weixin.mp.api.impl.AbstractWxMpServiceImpl; import java.util.concurrent.locks.Lock; /** * jodd-http方式实现 */ -public class WxMpServiceImpl extends AbstractWxMpServiceImpl { +public class WxMpServiceImpl extends AbstractWxMpServiceImpl { private HttpConnectionProvider httpClient; private ProxyInfo httpProxy; diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/request/WxMpKfAccountRequest.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/request/WxMpKfAccountRequest.java index b1f0fac8..85cdfe55 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/request/WxMpKfAccountRequest.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/request/WxMpKfAccountRequest.java @@ -1,12 +1,10 @@ package me.chanjar.weixin.mp.bean.kefu.request; -import java.io.Serializable; - -import org.apache.commons.lang3.builder.ToStringBuilder; - import com.google.gson.annotations.SerializedName; - import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; +import org.apache.commons.lang3.builder.ToStringBuilder; + +import java.io.Serializable; public class WxMpKfAccountRequest implements Serializable { private static final long serialVersionUID = -5451863610674856927L; @@ -16,7 +14,7 @@ public class WxMpKfAccountRequest implements Serializable { */ @SerializedName("kf_account") private String kfAccount; - + /** * nickname 客服昵称,最长6个汉字或12个英文字符 */ @@ -28,12 +26,16 @@ public class WxMpKfAccountRequest implements Serializable { */ @SerializedName("invite_wx") private String inviteWx; - + + public static Builder builder() { + return new Builder(); + } + @Override public String toString() { return ToStringBuilder.reflectionToString(this); } - + public String toJson() { return WxMpGsonBuilder.INSTANCE.create().toJson(this); } @@ -54,10 +56,6 @@ public class WxMpKfAccountRequest implements Serializable { this.nickName = nickName; } - public static Builder builder() { - return new Builder(); - } - public String getInviteWx() { return this.inviteWx; } @@ -67,39 +65,39 @@ public class WxMpKfAccountRequest implements Serializable { } public static class Builder { - private String kfAccount; - private String nickName; - private String inviteWx; - - public Builder kfAccount(String kfAccount) { - this.kfAccount = kfAccount; - return this; - } - - public Builder nickName(String nickName) { - this.nickName = nickName; - return this; - } - - public Builder inviteWx(String inviteWx) { - this.inviteWx = inviteWx; - return this; - } - - public Builder from(WxMpKfAccountRequest origin) { - this.kfAccount(origin.kfAccount); - this.nickName(origin.nickName); - this.inviteWx(origin.inviteWx); - return this; - } - - public WxMpKfAccountRequest build() { - WxMpKfAccountRequest m = new WxMpKfAccountRequest(); - m.kfAccount = this.kfAccount; - m.nickName = this.nickName; - m.inviteWx = this.inviteWx; - return m; - } + private String kfAccount; + private String nickName; + private String inviteWx; + + public Builder kfAccount(String kfAccount) { + this.kfAccount = kfAccount; + return this; + } + + public Builder nickName(String nickName) { + this.nickName = nickName; + return this; + } + + public Builder inviteWx(String inviteWx) { + this.inviteWx = inviteWx; + return this; + } + + public Builder from(WxMpKfAccountRequest origin) { + this.kfAccount(origin.kfAccount); + this.nickName(origin.nickName); + this.inviteWx(origin.inviteWx); + return this; + } + + public WxMpKfAccountRequest build() { + WxMpKfAccountRequest m = new WxMpKfAccountRequest(); + m.kfAccount = this.kfAccount; + m.nickName = this.nickName; + m.inviteWx = this.inviteWx; + return m; + } } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialDeleteRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialDeleteRequestExecutor.java index 082653b2..5349a0fa 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialDeleteRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialDeleteRequestExecutor.java @@ -1,7 +1,5 @@ package me.chanjar.weixin.mp.util.http.jodd; -import java.io.IOException; - import jodd.http.HttpConnectionProvider; import jodd.http.HttpRequest; import jodd.http.HttpResponse; @@ -11,10 +9,12 @@ import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.common.util.http.RequestHttp; import me.chanjar.weixin.mp.util.http.MaterialDeleteRequestExecutor; +import java.io.IOException; + /** * Created by ecoolper on 2017/5/5. */ -public class JoddMaterialDeleteRequestExecutor extends MaterialDeleteRequestExecutor { +public class JoddMaterialDeleteRequestExecutor extends MaterialDeleteRequestExecutor { public JoddMaterialDeleteRequestExecutor(RequestHttp requestHttp) { super(requestHttp); } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialNewsInfoRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialNewsInfoRequestExecutor.java index 083cfedc..6d6b0120 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialNewsInfoRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialNewsInfoRequestExecutor.java @@ -1,7 +1,5 @@ package me.chanjar.weixin.mp.util.http.jodd; -import java.io.IOException; - import jodd.http.HttpConnectionProvider; import jodd.http.HttpRequest; import jodd.http.HttpResponse; @@ -13,10 +11,12 @@ import me.chanjar.weixin.mp.bean.material.WxMpMaterialNews; import me.chanjar.weixin.mp.util.http.MaterialNewsInfoRequestExecutor; import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; +import java.io.IOException; + /** * Created by ecoolper on 2017/5/5. */ -public class JoddMaterialNewsInfoRequestExecutor extends MaterialNewsInfoRequestExecutor { +public class JoddMaterialNewsInfoRequestExecutor extends MaterialNewsInfoRequestExecutor { public JoddMaterialNewsInfoRequestExecutor(RequestHttp requestHttp) { super(requestHttp); } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialUploadRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialUploadRequestExecutor.java index 4c1fe480..8c9fdd0d 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialUploadRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialUploadRequestExecutor.java @@ -1,10 +1,5 @@ package me.chanjar.weixin.mp.util.http.jodd; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.Map; - import jodd.http.HttpConnectionProvider; import jodd.http.HttpRequest; import jodd.http.HttpResponse; @@ -17,10 +12,15 @@ import me.chanjar.weixin.mp.bean.material.WxMpMaterial; import me.chanjar.weixin.mp.bean.material.WxMpMaterialUploadResult; import me.chanjar.weixin.mp.util.http.MaterialUploadRequestExecutor; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.Map; + /** * Created by ecoolper on 2017/5/5. */ -public class JoddMaterialUploadRequestExecutor extends MaterialUploadRequestExecutor { +public class JoddMaterialUploadRequestExecutor extends MaterialUploadRequestExecutor { public JoddMaterialUploadRequestExecutor(RequestHttp requestHttp) { super(requestHttp); } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialVideoInfoRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialVideoInfoRequestExecutor.java index ed7bfc04..8d600bc6 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialVideoInfoRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialVideoInfoRequestExecutor.java @@ -1,7 +1,5 @@ package me.chanjar.weixin.mp.util.http.jodd; -import java.io.IOException; - import jodd.http.HttpConnectionProvider; import jodd.http.HttpRequest; import jodd.http.HttpResponse; @@ -12,10 +10,12 @@ import me.chanjar.weixin.common.util.http.RequestHttp; import me.chanjar.weixin.mp.bean.material.WxMpMaterialVideoInfoResult; import me.chanjar.weixin.mp.util.http.MaterialVideoInfoRequestExecutor; +import java.io.IOException; + /** * Created by ecoolper on 2017/5/5. */ -public class JoddMaterialVideoInfoRequestExecutor extends MaterialVideoInfoRequestExecutor { +public class JoddMaterialVideoInfoRequestExecutor extends MaterialVideoInfoRequestExecutor { public JoddMaterialVideoInfoRequestExecutor(RequestHttp requestHttp) { super(requestHttp); } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialVoiceAndImageDownloadRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialVoiceAndImageDownloadRequestExecutor.java index b8da949e..bc869600 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialVoiceAndImageDownloadRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMaterialVoiceAndImageDownloadRequestExecutor.java @@ -1,12 +1,5 @@ package me.chanjar.weixin.mp.util.http.jodd; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.commons.io.IOUtils; - import jodd.http.HttpConnectionProvider; import jodd.http.HttpRequest; import jodd.http.HttpResponse; @@ -16,12 +9,17 @@ import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.common.util.http.RequestHttp; import me.chanjar.weixin.common.util.json.WxGsonBuilder; import me.chanjar.weixin.mp.util.http.MaterialVoiceAndImageDownloadRequestExecutor; -import me.chanjar.weixin.mp.util.http.okhttp.OkhttpMaterialVoiceAndImageDownloadRequestExecutor; +import org.apache.commons.io.IOUtils; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; /** * Created by ecoolper on 2017/5/5. */ -public class JoddMaterialVoiceAndImageDownloadRequestExecutor extends MaterialVoiceAndImageDownloadRequestExecutor { +public class JoddMaterialVoiceAndImageDownloadRequestExecutor extends MaterialVoiceAndImageDownloadRequestExecutor { public JoddMaterialVoiceAndImageDownloadRequestExecutor(RequestHttp requestHttp, File tmpDirFile) { super(requestHttp, tmpDirFile); } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMediaImgUploadRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMediaImgUploadRequestExecutor.java index 82bfbf81..09309890 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMediaImgUploadRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddMediaImgUploadRequestExecutor.java @@ -1,8 +1,5 @@ package me.chanjar.weixin.mp.util.http.jodd; -import java.io.File; -import java.io.IOException; - import jodd.http.HttpConnectionProvider; import jodd.http.HttpRequest; import jodd.http.HttpResponse; @@ -13,10 +10,13 @@ import me.chanjar.weixin.common.util.http.RequestHttp; import me.chanjar.weixin.mp.bean.material.WxMediaImgUploadResult; import me.chanjar.weixin.mp.util.http.MediaImgUploadRequestExecutor; +import java.io.File; +import java.io.IOException; + /** * Created by ecoolper on 2017/5/5. */ -public class JoddMediaImgUploadRequestExecutor extends MediaImgUploadRequestExecutor { +public class JoddMediaImgUploadRequestExecutor extends MediaImgUploadRequestExecutor { public JoddMediaImgUploadRequestExecutor(RequestHttp requestHttp) { super(requestHttp); } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddQrCodeRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddQrCodeRequestExecutor.java index 1191751c..36ae7b4d 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddQrCodeRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/jodd/JoddQrCodeRequestExecutor.java @@ -1,12 +1,5 @@ package me.chanjar.weixin.mp.util.http.jodd; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.URLEncoder; -import java.util.UUID; - import jodd.http.HttpConnectionProvider; import jodd.http.HttpRequest; import jodd.http.HttpResponse; @@ -19,10 +12,17 @@ import me.chanjar.weixin.common.util.http.RequestHttp; import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket; import me.chanjar.weixin.mp.util.http.QrCodeRequestExecutor; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.URLEncoder; +import java.util.UUID; + /** * Created by ecoolper on 2017/5/5. */ -public class JoddQrCodeRequestExecutor extends QrCodeRequestExecutor { +public class JoddQrCodeRequestExecutor extends QrCodeRequestExecutor { public JoddQrCodeRequestExecutor(RequestHttp requestHttp) { super(requestHttp); } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialDeleteRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialDeleteRequestExecutor.java index 5da55877..17e3ae55 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialDeleteRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialDeleteRequestExecutor.java @@ -1,15 +1,14 @@ package me.chanjar.weixin.mp.util.http.okhttp; -import java.io.IOException; - import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.common.util.http.RequestExecutor; import me.chanjar.weixin.common.util.http.RequestHttp; import me.chanjar.weixin.common.util.http.okhttp.OkhttpProxyInfo; import me.chanjar.weixin.mp.util.http.MaterialDeleteRequestExecutor; import okhttp3.*; +import java.io.IOException; + /** * Created by ecoolper on 2017/5/5. */ diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialNewsInfoRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialNewsInfoRequestExecutor.java index c7efbb89..921915ff 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialNewsInfoRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialNewsInfoRequestExecutor.java @@ -1,7 +1,5 @@ package me.chanjar.weixin.mp.util.http.okhttp; -import java.io.IOException; - import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.common.util.http.RequestHttp; @@ -11,6 +9,8 @@ import me.chanjar.weixin.mp.util.http.MaterialNewsInfoRequestExecutor; import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; import okhttp3.*; +import java.io.IOException; + /** * Created by ecoolper on 2017/5/5. */ diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialUploadRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialUploadRequestExecutor.java index 4be74cda..a1e3f618 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialUploadRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialUploadRequestExecutor.java @@ -1,21 +1,8 @@ package me.chanjar.weixin.mp.util.http.okhttp; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.Map; - -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.mime.HttpMultipartMode; -import org.apache.http.entity.mime.MultipartEntityBuilder; - import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.common.util.http.RequestHttp; -import me.chanjar.weixin.common.util.http.apache.Utf8ResponseHandler; import me.chanjar.weixin.common.util.http.okhttp.OkhttpProxyInfo; import me.chanjar.weixin.common.util.json.WxGsonBuilder; import me.chanjar.weixin.mp.bean.material.WxMpMaterial; @@ -23,6 +10,11 @@ import me.chanjar.weixin.mp.bean.material.WxMpMaterialUploadResult; import me.chanjar.weixin.mp.util.http.MaterialUploadRequestExecutor; import okhttp3.*; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.Map; + /** * Created by ecoolper on 2017/5/5. */ @@ -66,7 +58,7 @@ public class OkhttpMaterialUploadRequestExecutor extends MaterialUploadRequestEx if (material.getForm() != null) { bodyBuilder.addFormDataPart("description", WxGsonBuilder.create().toJson(form)); } - RequestBody body =bodyBuilder.build(); + RequestBody body = bodyBuilder.build(); Request request = new Request.Builder().url(uri).post(body).build(); Response response = client.newCall(request).execute(); String responseContent = response.body().string(); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialVideoInfoRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialVideoInfoRequestExecutor.java index c431d70a..e296a849 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialVideoInfoRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialVideoInfoRequestExecutor.java @@ -1,7 +1,5 @@ package me.chanjar.weixin.mp.util.http.okhttp; -import java.io.IOException; - import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.common.util.http.RequestHttp; @@ -10,6 +8,8 @@ import me.chanjar.weixin.mp.bean.material.WxMpMaterialVideoInfoResult; import me.chanjar.weixin.mp.util.http.MaterialVideoInfoRequestExecutor; import okhttp3.*; +import java.io.IOException; + /** * Created by ecoolper on 2017/5/5. */ @@ -38,7 +38,7 @@ public class OkhttpMaterialVideoInfoRequestExecutor extends MaterialVideoInfoReq //得到httpClient OkHttpClient client = clientBuilder.build(); - RequestBody requestBody =new FormBody.Builder().add("media_id", materialId).build(); + RequestBody requestBody = new FormBody.Builder().add("media_id", materialId).build(); Request request = new Request.Builder().url(uri).post(requestBody).build(); Response response = client.newCall(request).execute(); String responseContent = response.body().string(); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialVoiceAndImageDownloadRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialVoiceAndImageDownloadRequestExecutor.java index 3cd1eb98..e6393b82 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialVoiceAndImageDownloadRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMaterialVoiceAndImageDownloadRequestExecutor.java @@ -1,12 +1,5 @@ package me.chanjar.weixin.mp.util.http.okhttp; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; - -import org.apache.commons.io.IOUtils; - import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.common.util.http.RequestHttp; @@ -14,6 +7,12 @@ import me.chanjar.weixin.common.util.http.okhttp.OkhttpProxyInfo; import me.chanjar.weixin.common.util.json.WxGsonBuilder; import me.chanjar.weixin.mp.util.http.MaterialVoiceAndImageDownloadRequestExecutor; import okhttp3.*; +import org.apache.commons.io.IOUtils; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; /** * Created by ecoolper on 2017/5/5. diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMediaImgUploadRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMediaImgUploadRequestExecutor.java index 790dd17e..af29e532 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMediaImgUploadRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpMediaImgUploadRequestExecutor.java @@ -1,8 +1,5 @@ package me.chanjar.weixin.mp.util.http.okhttp; -import java.io.File; -import java.io.IOException; - import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.common.util.http.RequestHttp; @@ -11,6 +8,9 @@ import me.chanjar.weixin.mp.bean.material.WxMediaImgUploadResult; import me.chanjar.weixin.mp.util.http.MediaImgUploadRequestExecutor; import okhttp3.*; +import java.io.File; +import java.io.IOException; + /** * Created by ecoolper on 2017/5/5. */ diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpQrCodeRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpQrCodeRequestExecutor.java index b2cb372f..463d69ac 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpQrCodeRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/okhttp/OkhttpQrCodeRequestExecutor.java @@ -1,11 +1,5 @@ package me.chanjar.weixin.mp.util.http.okhttp; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.UUID; - import jodd.util.MimeTypes; import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.exception.WxErrorException; @@ -16,6 +10,12 @@ import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket; import me.chanjar.weixin.mp.util.http.QrCodeRequestExecutor; import okhttp3.*; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.UUID; + /** * Created by ecoolper on 2017/5/5. */