From d7d9734bf119ea66fbd63a3e92de39afbdbd4771 Mon Sep 17 00:00:00 2001 From: codepiano Date: Tue, 21 Jul 2015 22:57:50 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E6=B0=B8=E4=B9=85=E7=B4=A0?= =?UTF-8?q?=E6=9D=90=E7=9B=B8=E5=85=B3=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../chanjar/weixin/common/api/WxConsts.java | 7 + .../weixin/mp/api/WxMpServiceImpl.java | 193 ++++++++++---- .../chanjar/weixin/mp/bean/WxMpMassNews.java | 44 +++- .../chanjar/weixin/mp/bean/WxMpMaterial.java | 67 +++++ .../mp/bean/WxMpMaterialArticleUpdate.java | 45 ++++ .../weixin/mp/bean/WxMpMaterialNews.java | 141 +++++++++++ .../bean/result/WxMpMaterialCountResult.java | 50 ++++ .../WxMpMaterialFileBatchGetResult.java | 85 +++++++ .../WxMpMaterialNewsBatchGetResult.java | 78 ++++++ .../bean/result/WxMpMaterialUploadResult.java | 38 +++ .../result/WxMpMaterialVideoInfoResult.java | 46 ++++ .../http/MaterialDeleteRequestExecutor.java | 47 ++++ .../http/MaterialNewsInfoRequestExecutor.java | 48 ++++ .../http/MaterialUploadRequestExecutor.java | 58 +++++ .../MaterialVideoInfoRequestExecutor.java | 47 ++++ ...lVoiceAndImageDownloadRequestExecutor.java | 65 +++++ .../weixin/mp/util/json/WxMpGsonBuilder.java | 17 +- .../json/WxMpMassNewsArticleGsonAdapter.java | 72 ++++++ .../mp/util/json/WxMpMassNewsGsonAdapter.java | 35 ++- .../WxMpMaterialArticleUpdateGsonAdapter.java | 30 +++ .../json/WxMpMaterialCountResultAdapter.java | 41 +++ .../WxMpMaterialFileBatchGetGsonAdapter.java | 41 +++ ...MpMaterialFileBatchGetGsonItemAdapter.java | 37 +++ .../WxMpMaterialNewsArticleGsonAdapter.java | 72 ++++++ .../WxMpMaterialNewsBatchGetGsonAdapter.java | 41 +++ ...MpMaterialNewsBatchGetGsonItemAdapter.java | 36 +++ .../json/WxMpMaterialNewsGsonAdapter.java | 44 ++++ .../json/WxMpMaterialUploadResultAdapter.java | 35 +++ .../WxMpMaterialVideoInfoResultAdapter.java | 30 +++ .../weixin/mp/api/WxMpMaterialAPITest.java | 237 ++++++++++++++++++ 30 files changed, 1745 insertions(+), 82 deletions(-) create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMaterial.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMaterialArticleUpdate.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMaterialNews.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialCountResult.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialFileBatchGetResult.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialNewsBatchGetResult.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialUploadResult.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialVideoInfoResult.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialDeleteRequestExecutor.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialNewsInfoRequestExecutor.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialUploadRequestExecutor.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialVideoInfoRequestExecutor.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialVoiceAndImageDownloadRequestExecutor.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassNewsArticleGsonAdapter.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialArticleUpdateGsonAdapter.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialCountResultAdapter.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialFileBatchGetGsonAdapter.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialFileBatchGetGsonItemAdapter.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialNewsArticleGsonAdapter.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialNewsBatchGetGsonAdapter.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialNewsBatchGetGsonItemAdapter.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialNewsGsonAdapter.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialUploadResultAdapter.java create mode 100644 weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialVideoInfoResultAdapter.java create mode 100644 weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxMpMaterialAPITest.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 a6bb1b669c..454c6f2366 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 @@ -137,4 +137,11 @@ public class WxConsts { /** 弹出授权页面,可通过openid拿到昵称、性别、所在地。并且,即使在未关注的情况下,只要用户授权,也能获取其信息 */ public static final String OAUTH2_SCOPE_USER_INFO = "snsapi_userinfo"; + /////////////////////// + // 永久素材类型 + /////////////////////// + public static final String MATERIAL_NEWS = "news"; + public static final String MATERIAL_VOICE = "voice"; + public static final String MATERIAL_IMAGE = "image"; + public static final String MATERIAL_VIDEO = "video"; } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpServiceImpl.java index 0139ed0fca..61960113a2 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpServiceImpl.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpServiceImpl.java @@ -1,5 +1,6 @@ package me.chanjar.weixin.mp.api; +import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; @@ -7,10 +8,9 @@ import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.thoughtworks.xstream.XStream; - import me.chanjar.weixin.common.bean.WxAccessToken; -import me.chanjar.weixin.common.bean.WxMenu; import me.chanjar.weixin.common.bean.WxJsapiSignature; +import me.chanjar.weixin.common.bean.WxMenu; import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.bean.result.WxMediaUploadResult; import me.chanjar.weixin.common.exception.WxErrorException; @@ -26,9 +26,8 @@ import me.chanjar.weixin.common.util.xml.XStreamInitializer; import me.chanjar.weixin.mp.bean.*; import me.chanjar.weixin.mp.bean.result.*; -import me.chanjar.weixin.mp.util.http.QrCodeRequestExecutor; +import me.chanjar.weixin.mp.util.http.*; import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; - import org.apache.http.Consts; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; @@ -51,7 +50,6 @@ import java.io.IOException; import java.io.InputStream; import java.io.StringReader; -import java.math.BigDecimal; import java.security.NoSuchAlgorithmException; import java.util.*; @@ -102,8 +100,7 @@ public String getAccessToken(boolean forceRefresh) throws WxErrorException { if (wxMpConfigStorage.isAccessTokenExpired()) { String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" + "&appid=" + wxMpConfigStorage.getAppId() - + "&secret=" + wxMpConfigStorage.getSecret() - ; + + "&secret=" + wxMpConfigStorage.getSecret(); try { HttpGet httpGet = new HttpGet(url); if (httpProxy != null) { @@ -179,12 +176,12 @@ public void customMessageSend(WxMpCustomMessage message) throws WxErrorException String url = "https://api.weixin.qq.com/cgi-bin/message/custom/send"; execute(new SimplePostRequestExecutor(), url, message.toJson()); } - + public void menuCreate(WxMenu menu) throws WxErrorException { String url = "https://api.weixin.qq.com/cgi-bin/menu/create"; execute(new SimplePostRequestExecutor(), url, menu.toJson()); } - + public void menuDelete() throws WxErrorException { String url = "https://api.weixin.qq.com/cgi-bin/menu/delete"; execute(new SimpleGetRequestExecutor(), url, null); @@ -205,31 +202,117 @@ public WxMenu menuGet() throws WxErrorException { } public WxMediaUploadResult mediaUpload(String mediaType, String fileType, InputStream inputStream) throws WxErrorException, IOException { - return mediaUpload(mediaType,FileUtils.createTmpFile(inputStream, UUID.randomUUID().toString(), fileType)); + return mediaUpload(mediaType, FileUtils.createTmpFile(inputStream, UUID.randomUUID().toString(), fileType)); } - + public WxMediaUploadResult mediaUpload(String mediaType, File file) throws WxErrorException { String url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?type=" + mediaType; return execute(new MediaUploadRequestExecutor(), url, file); } - + public File mediaDownload(String media_id) throws WxErrorException { String url = "http://file.api.weixin.qq.com/cgi-bin/media/get"; return execute(new MediaDownloadRequestExecutor(wxMpConfigStorage.getTmpDirFile()), url, "media_id=" + media_id); } + public WxMpMaterialUploadResult materialFileUpload(String mediaType, WxMpMaterial material) throws WxErrorException { + String url = "https://api.weixin.qq.com/cgi-bin/material/add_material?type=" + mediaType; + return execute(new MaterialUploadRequestExecutor(), url, material); + } + + public WxMpMaterialUploadResult materialNewsUpload(WxMpMaterialNews news) throws WxErrorException { + if (news == null || news.isEmpty()) { + throw new IllegalArgumentException("news is empty!"); + } + String url = "https://api.weixin.qq.com/cgi-bin/material/add_news"; + String responseContent = post(url, news.toJson()); + return WxMpMaterialUploadResult.fromJson(responseContent); + } + + public InputStream materialImageOrVoiceDownload(String media_id) throws WxErrorException { + String url = "https://api.weixin.qq.com/cgi-bin/material/get_material"; + return execute(new MaterialVoiceAndImageDownloadRequestExecutor(wxMpConfigStorage.getTmpDirFile()), url, media_id); + } + + public WxMpMaterialVideoInfoResult materialVideoInfo(String media_id) throws WxErrorException { + String url = "https://api.weixin.qq.com/cgi-bin/material/get_material"; + return execute(new MaterialVideoInfoRequestExecutor(), url, media_id); + } + + public WxMpMaterialNews materialNewsInfo(String media_id) throws WxErrorException { + String url = "https://api.weixin.qq.com/cgi-bin/material/get_material"; + return execute(new MaterialNewsInfoRequestExecutor(), url, media_id); + } + + public boolean materialNewsUpdate(WxMpMaterialArticleUpdate wxMpMaterialArticleUpdate) throws WxErrorException { + String url = "https://api.weixin.qq.com/cgi-bin/material/update_news"; + String responseText = post(url, wxMpMaterialArticleUpdate.toJson()); + WxError wxError = WxError.fromJson(responseText); + if (wxError.getErrorCode() == 0) { + return true; + } else { + throw new WxErrorException(wxError); + } + } + + public boolean materialDelete(String media_id) throws WxErrorException { + String url = "https://api.weixin.qq.com/cgi-bin/material/del_material"; + return execute(new MaterialDeleteRequestExecutor(), url, media_id); + } + + public WxMpMaterialCountResult materialCount() throws WxErrorException { + String url = "https://api.weixin.qq.com/cgi-bin/material/get_materialcount"; + String responseText = get(url, null); + WxError wxError = WxError.fromJson(responseText); + if (wxError.getErrorCode() == 0) { + return WxMpGsonBuilder.create().fromJson(responseText, WxMpMaterialCountResult.class); + } else { + throw new WxErrorException(wxError); + } + } + + public WxMpMaterialNewsBatchGetResult materialNewsBatchGet(String type, int offset, int count) throws WxErrorException { + String url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material"; + Map params = new HashMap(); + params.put("type", type); + params.put("offset", offset); + params.put("count", count); + String responseText = post(url, new Gson().toJson(params)); + WxError wxError = WxError.fromJson(responseText); + if (wxError.getErrorCode() == 0) { + return WxMpGsonBuilder.create().fromJson(responseText, WxMpMaterialNewsBatchGetResult.class); + } else { + throw new WxErrorException(wxError); + } + } + + public WxMpMaterialFileBatchGetResult materialFileBatchGet(String type, int offset, int count) throws WxErrorException { + String url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material"; + Map params = new HashMap(); + params.put("type", type); + params.put("offset", offset); + params.put("count", count); + String responseText = post(url, new Gson().toJson(params)); + WxError wxError = WxError.fromJson(responseText); + if (wxError.getErrorCode() == 0) { + return WxMpGsonBuilder.create().fromJson(responseText, WxMpMaterialFileBatchGetResult.class); + } else { + throw new WxErrorException(wxError); + } + } + public WxMpMassUploadResult massNewsUpload(WxMpMassNews news) throws WxErrorException { String url = "https://api.weixin.qq.com/cgi-bin/media/uploadnews"; String responseContent = execute(new SimplePostRequestExecutor(), url, news.toJson()); return WxMpMassUploadResult.fromJson(responseContent); } - + public WxMpMassUploadResult massVideoUpload(WxMpMassVideo video) throws WxErrorException { String url = "http://file.api.weixin.qq.com/cgi-bin/media/uploadvideo"; String responseContent = execute(new SimplePostRequestExecutor(), url, video.toJson()); return WxMpMassUploadResult.fromJson(responseContent); } - + public WxMpMassSendResult massGroupMessageSend(WxMpMassGroupMessage message) throws WxErrorException { String url = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall"; String responseContent = execute(new SimplePostRequestExecutor(), url, message.toJson()); @@ -241,17 +324,17 @@ public WxMpMassSendResult massOpenIdsMessageSend(WxMpMassOpenIdsMessage message) String responseContent = execute(new SimplePostRequestExecutor(), url, message.toJson()); return WxMpMassSendResult.fromJson(responseContent); } - + public WxMpGroup groupCreate(String name) throws WxErrorException { String url = "https://api.weixin.qq.com/cgi-bin/groups/create"; JsonObject json = new JsonObject(); JsonObject groupJson = new JsonObject(); json.add("group", groupJson); groupJson.addProperty("name", name); - + String responseContent = execute( - new SimplePostRequestExecutor(), - url, + new SimplePostRequestExecutor(), + url, json.toString()); return WxMpGroup.fromJson(responseContent); } @@ -264,9 +347,10 @@ public List groupGet() throws WxErrorException { * 查询时返回的是 { groups : [ { id : ..., name : ..., count : ... }, ... ] } */ JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); - return WxMpGsonBuilder.INSTANCE.create().fromJson(tmpJsonElement.getAsJsonObject().get("groups"), new TypeToken>(){}.getType()); + return WxMpGsonBuilder.INSTANCE.create().fromJson(tmpJsonElement.getAsJsonObject().get("groups"), new TypeToken>() { + }.getType()); } - + public long userGetGroup(String openid) throws WxErrorException { String url = "https://api.weixin.qq.com/cgi-bin/groups/getid"; JsonObject o = new JsonObject(); @@ -275,12 +359,12 @@ public long userGetGroup(String openid) throws WxErrorException { JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); return GsonHelper.getAsLong(tmpJsonElement.getAsJsonObject().get("groupid")); } - + public void groupUpdate(WxMpGroup group) throws WxErrorException { String url = "https://api.weixin.qq.com/cgi-bin/groups/update"; execute(new SimplePostRequestExecutor(), url, group.toJson()); } - + public void userUpdateGroup(String openid, long to_groupid) throws WxErrorException { String url = "https://api.weixin.qq.com/cgi-bin/groups/members/update"; JsonObject json = new JsonObject(); @@ -288,7 +372,7 @@ public void userUpdateGroup(String openid, long to_groupid) throws WxErrorExcept json.addProperty("to_groupid", to_groupid); execute(new SimplePostRequestExecutor(), url, json.toString()); } - + public void userUpdateRemark(String openid, String remark) throws WxErrorException { String url = "https://api.weixin.qq.com/cgi-bin/user/info/updateremark"; JsonObject json = new JsonObject(); @@ -296,25 +380,25 @@ public void userUpdateRemark(String openid, String remark) throws WxErrorExcepti json.addProperty("remark", remark); execute(new SimplePostRequestExecutor(), url, json.toString()); } - + public WxMpUser userInfo(String openid, String lang) throws WxErrorException { String url = "https://api.weixin.qq.com/cgi-bin/user/info"; lang = lang == null ? "zh_CN" : lang; String responseContent = execute(new SimpleGetRequestExecutor(), url, "openid=" + openid + "&lang=" + lang); return WxMpUser.fromJson(responseContent); } - + public WxMpUserList userList(String next_openid) throws WxErrorException { String url = "https://api.weixin.qq.com/cgi-bin/user/get"; String responseContent = execute(new SimpleGetRequestExecutor(), url, next_openid == null ? null : "next_openid=" + next_openid); return WxMpUserList.fromJson(responseContent); } - + public WxMpQrCodeTicket qrCodeCreateTmpTicket(int scene_id, Integer expire_seconds) throws WxErrorException { String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create"; JsonObject json = new JsonObject(); json.addProperty("action_name", "QR_SCENE"); - if(expire_seconds != null) { + if (expire_seconds != null) { json.addProperty("expire_seconds", expire_seconds); } JsonObject actionInfo = new JsonObject(); @@ -325,7 +409,7 @@ public WxMpQrCodeTicket qrCodeCreateTmpTicket(int scene_id, Integer expire_secon String responseContent = execute(new SimplePostRequestExecutor(), url, json.toString()); return WxMpQrCodeTicket.fromJson(responseContent); } - + public WxMpQrCodeTicket qrCodeCreateLastTicket(int scene_id) throws WxErrorException { String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create"; JsonObject json = new JsonObject(); @@ -351,12 +435,12 @@ public WxMpQrCodeTicket qrCodeCreateLastTicket(String scene_str) throws WxErrorE String responseContent = execute(new SimplePostRequestExecutor(), url, json.toString()); return WxMpQrCodeTicket.fromJson(responseContent); } - + public File qrCodePicture(WxMpQrCodeTicket ticket) throws WxErrorException { String url = "https://mp.weixin.qq.com/cgi-bin/showqrcode"; return execute(new QrCodeRequestExecutor(), url, ticket); } - + public String shortUrl(String long_url) throws WxErrorException { String url = "https://api.weixin.qq.com/cgi-bin/shorturl"; JsonObject o = new JsonObject(); @@ -387,7 +471,7 @@ public String oauth2buildAuthorizationUrl(String scope, String state) { @Override public String oauth2buildAuthorizationUrl(String redirectURI, String scope, String state) { - String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" ; + String url = "https://open.weixin.qq.com/connect/oauth2/authorize?"; url += "appid=" + wxMpConfigStorage.getAppId(); url += "&redirect_uri=" + URIUtil.encodeURIComponent(redirectURI); url += "&response_type=code"; @@ -402,7 +486,7 @@ public String oauth2buildAuthorizationUrl(String redirectURI, String scope, Stri @Override public WxMpOAuth2AccessToken oauth2getAccessToken(String code) throws WxErrorException { String url = "https://api.weixin.qq.com/sns/oauth2/access_token?"; - url += "appid=" + wxMpConfigStorage.getAppId(); + url += "appid=" + wxMpConfigStorage.getAppId(); url += "&secret=" + wxMpConfigStorage.getSecret(); url += "&code=" + code; url += "&grant_type=authorization_code"; @@ -499,7 +583,8 @@ public List getUserSummary(Date beginDate, Date endDate) throws param.addProperty("end_date", SIMPLE_DATE_FORMAT.format(endDate)); String responseContent = post(url, param.toString()); JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); - return WxMpGsonBuilder.INSTANCE.create().fromJson(tmpJsonElement.getAsJsonObject().get("list"), new TypeToken>(){}.getType()); + return WxMpGsonBuilder.INSTANCE.create().fromJson(tmpJsonElement.getAsJsonObject().get("list"), new TypeToken>() { + }.getType()); } @Override @@ -510,7 +595,8 @@ public List getUserCumulate(Date beginDate, Date endDate) thro param.addProperty("end_date", SIMPLE_DATE_FORMAT.format(endDate)); String responseContent = post(url, param.toString()); JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); - return WxMpGsonBuilder.INSTANCE.create().fromJson(tmpJsonElement.getAsJsonObject().get("list"), new TypeToken>(){}.getType()); + return WxMpGsonBuilder.INSTANCE.create().fromJson(tmpJsonElement.getAsJsonObject().get("list"), new TypeToken>() { + }.getType()); } public String get(String url, String queryParam) throws WxErrorException { @@ -523,6 +609,7 @@ public String post(String url, String postData) throws WxErrorException { /** * 向微信端发送请求,在这里执行的策略是当发生access_token过期时才去刷新,然后重新执行请求,而不是全局定时请求 + * * @param executor * @param uri * @param data @@ -551,17 +638,17 @@ public T execute(RequestExecutor executor, String uri, E data) thro throw e; } } - } while(++retryTimes < maxRetryTimes); + } while (++retryTimes < maxRetryTimes); throw new RuntimeException("微信服务端异常,超出重试次数"); } protected T executeInternal(RequestExecutor executor, String uri, E data) throws WxErrorException { String accessToken = getAccessToken(false); - + String uriWithAccessToken = uri; uriWithAccessToken += uri.indexOf('?') == -1 ? "?access_token=" + accessToken : "&access_token=" + accessToken; - + try { return executor.execute(getHttpclient(), httpProxy, uriWithAccessToken, data); } catch (WxErrorException e) { @@ -599,9 +686,9 @@ public void setWxMpConfigStorage(WxMpConfigStorage wxConfigProvider) { String http_proxy_username = wxMpConfigStorage.getHttp_proxy_username(); String http_proxy_password = wxMpConfigStorage.getHttp_proxy_password(); - if(StringUtils.isNotBlank(http_proxy_host)) { + if (StringUtils.isNotBlank(http_proxy_host)) { // 使用代理服务器 - if(StringUtils.isNotBlank(http_proxy_username)) { + if (StringUtils.isNotBlank(http_proxy_username)) { // 需要用户认证的代理服务器 CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( @@ -643,7 +730,7 @@ public WxMpPrepayIdResult getPrepayId(String openId, String outTradeNo, double a packageParams.put("body", body); packageParams.put("out_trade_no", outTradeNo); - packageParams.put("total_fee", (int)(amt*100) + ""); + packageParams.put("total_fee", (int) (amt * 100) + ""); packageParams.put("spbill_create_ip", ip); packageParams.put("notify_url", callbackUrl); packageParams.put("trade_type", tradeType); @@ -651,18 +738,18 @@ public WxMpPrepayIdResult getPrepayId(String openId, String outTradeNo, double a String sign = WxCryptUtil.createSign(packageParams, wxMpConfigStorage.getPartnerKey()); String xml = "" + - "" + wxMpConfigStorage.getAppId() + "" + - "" + wxMpConfigStorage.getPartnerId() + "" + - "" + nonce_str + "" + - "" + sign + "" + - "" + - "" + outTradeNo + "" + - "" + packageParams.get("total_fee") + "" + - "" + ip + "" + - "" + callbackUrl + "" + - "" + tradeType + "" + - "" + openId + "" + - ""; + "" + wxMpConfigStorage.getAppId() + "" + + "" + wxMpConfigStorage.getPartnerId() + "" + + "" + nonce_str + "" + + "" + sign + "" + + "" + + "" + outTradeNo + "" + + "" + packageParams.get("total_fee") + "" + + "" + ip + "" + + "" + callbackUrl + "" + + "" + tradeType + "" + + "" + openId + "" + + ""; HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/pay/unifiedorder"); if (httpProxy != null) { @@ -690,7 +777,7 @@ public Map getJSSDKPayInfo(String openId, String outTradeNo, dou WxMpPrepayIdResult wxMpPrepayIdResult = getPrepayId(openId, outTradeNo, amt, body, tradeType, ip, callbackUrl); String prepayId = wxMpPrepayIdResult.getPrepay_id(); if (prepayId == null || prepayId.equals("")) { - throw new RuntimeException("get prepayid error"); + throw new RuntimeException("get prepayid error"); } Map payInfo = new HashMap(); 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 f76028382b..215bff5280 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 @@ -8,25 +8,29 @@ /** * 群发时用到的图文消息素材 - * @author chanjarster * + * @author chanjarster */ public class WxMpMassNews implements Serializable { private List articles = new ArrayList(); - + public List getArticles() { return articles; } - + public void addArticle(WxMpMassNewsArticle article) { this.articles.add(article); } - + public String toJson() { return WxMpGsonBuilder.INSTANCE.create().toJson(this); } - + + public boolean isEmpty() { + return articles == null || articles.isEmpty(); + } + /** *
    * 群发图文消息article
@@ -38,8 +42,8 @@ public String toJson() {
    * 6. digest          图文消息的描述
    * 7, showCoverPic  是否显示封面,true为显示,false为不显示
    * 
- * @author chanjarster * + * @author chanjarster */ public static class WxMpMassNewsArticle { /** @@ -70,49 +74,73 @@ public static class WxMpMassNewsArticle { * 是否显示封面,true为显示,false为不显示 */ private boolean showCoverPic; - + public String getThumbMediaId() { return thumbMediaId; } + public void setThumbMediaId(String thumbMediaId) { this.thumbMediaId = thumbMediaId; } + public String getAuthor() { return author; } + public void setAuthor(String author) { this.author = author; } + public String getTitle() { return title; } + public void setTitle(String title) { this.title = title; } + public String getContentSourceUrl() { return contentSourceUrl; } + public void setContentSourceUrl(String contentSourceUrl) { this.contentSourceUrl = contentSourceUrl; } + public String getContent() { return content; } + public void setContent(String content) { this.content = content; } + public String getDigest() { return digest; } + public void setDigest(String digest) { this.digest = digest; } + public boolean isShowCoverPic() { return showCoverPic; } + public void setShowCoverPic(boolean showCoverPic) { this.showCoverPic = showCoverPic; } - + + @Override + public String toString() { + return "WxMpMassNewsArticle [" + "thumbMediaId=" + thumbMediaId + ", author=" + author + ", title=" + title + + ", contentSourceUrl=" + contentSourceUrl + ", content=" + content + ", digest=" + digest + + ", showCoverPic=" + showCoverPic + "]"; + } + } + + @Override + public String toString() { + return "WxMpMassNews [" + "articles=" + articles + "]"; } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMaterial.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMaterial.java new file mode 100644 index 0000000000..582825aa99 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMaterial.java @@ -0,0 +1,67 @@ +package me.chanjar.weixin.mp.bean; + +import java.io.File; +import java.util.HashMap; +import java.util.Map; + +public class WxMpMaterial { + + private String name; + private File file; + private String videoTitle; + private String videoIntroduction; + + public WxMpMaterial() { + } + + public WxMpMaterial(String name, File file, String videoTitle, String videoIntroduction) { + this.name = name; + this.file = file; + this.videoTitle = videoTitle; + this.videoIntroduction = videoIntroduction; + } + + public Map getForm() { + Map form = new HashMap(); + form.put("title", videoTitle); + form.put("introduction", videoIntroduction); + return form; + } + + public String getVideoTitle() { + return videoTitle; + } + + public void setVideoTitle(String videoTitle) { + this.videoTitle = videoTitle; + } + + public String getVideoIntroduction() { + return videoIntroduction; + } + + public void setVideoIntroduction(String videoIntroduction) { + this.videoIntroduction = videoIntroduction; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public File getFile() { + return file; + } + + public void setFile(File file) { + this.file = file; + } + + @Override + public String toString() { + return "WxMpMaterial [" + "name=" + name + ", file=" + file + ", videoTitle=" + videoTitle + ", videoIntroduction=" + videoIntroduction + "]"; + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMaterialArticleUpdate.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMaterialArticleUpdate.java new file mode 100644 index 0000000000..be8e75f8e2 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMaterialArticleUpdate.java @@ -0,0 +1,45 @@ +package me.chanjar.weixin.mp.bean; + +import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; + +import java.io.Serializable; + +public class WxMpMaterialArticleUpdate implements Serializable { + + private String mediaId; + private int index; + private WxMpMaterialNews.WxMpMaterialNewsArticle articles; + + public String getMediaId() { + return mediaId; + } + + public void setMediaId(String mediaId) { + this.mediaId = mediaId; + } + + public int getIndex() { + return index; + } + + public void setIndex(int index) { + this.index = index; + } + + public WxMpMaterialNews.WxMpMaterialNewsArticle getArticles() { + return articles; + } + + public void setArticles(WxMpMaterialNews.WxMpMaterialNewsArticle articles) { + this.articles = articles; + } + + public String toJson() { + return WxMpGsonBuilder.create().toJson(this); + } + + @Override + public String toString() { + return "WxMpMaterialArticleUpdate [" + "mediaId=" + mediaId + ", index=" + index + ", articles=" + articles + "]"; + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMaterialNews.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMaterialNews.java new file mode 100644 index 0000000000..af64464dca --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMaterialNews.java @@ -0,0 +1,141 @@ +package me.chanjar.weixin.mp.bean; + +import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +public class WxMpMaterialNews implements Serializable { + + private List articles = new ArrayList(); + + public List getArticles() { + return articles; + } + + public void addArticle(WxMpMaterialNewsArticle article) { + this.articles.add(article); + } + + public String toJson() { + return WxMpGsonBuilder.INSTANCE.create().toJson(this); + } + + public boolean isEmpty() { + return articles == null || articles.isEmpty(); + } + + /** + *
+   * 群发图文消息article
+   * 1. thumbMediaId  (必填) 图文消息缩略图的media_id,可以在基础支持-上传多媒体文件接口中获得
+   * 2. author          图文消息的作者
+   * 3. title           (必填) 图文消息的标题
+   * 4. contentSourceUrl 在图文消息页面点击“阅读原文”后的页面链接
+   * 5. content (必填)  图文消息页面的内容,支持HTML标签
+   * 6. digest          图文消息的描述
+   * 7, showCoverPic  是否显示封面,true为显示,false为不显示
+   * 
+ * + * @author chanjarster + */ + public static class WxMpMaterialNewsArticle { + /** + * (必填) 图文消息缩略图的media_id,可以在基础支持-上传多媒体文件接口中获得 + */ + private String thumbMediaId; + /** + * 图文消息的作者 + */ + private String author; + /** + * (必填) 图文消息的标题 + */ + private String title; + /** + * 在图文消息页面点击“阅读原文”后的页面链接 + */ + private String contentSourceUrl; + /** + * (必填) 图文消息页面的内容,支持HTML标签 + */ + private String content; + /** + * 图文消息的描述 + */ + private String digest; + /** + * 是否显示封面,true为显示,false为不显示 + */ + private boolean showCoverPic; + + public String getThumbMediaId() { + return thumbMediaId; + } + + public void setThumbMediaId(String thumbMediaId) { + this.thumbMediaId = thumbMediaId; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getContentSourceUrl() { + return contentSourceUrl; + } + + public void setContentSourceUrl(String contentSourceUrl) { + this.contentSourceUrl = contentSourceUrl; + } + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } + + public String getDigest() { + return digest; + } + + public void setDigest(String digest) { + this.digest = digest; + } + + public boolean isShowCoverPic() { + return showCoverPic; + } + + public void setShowCoverPic(boolean showCoverPic) { + this.showCoverPic = showCoverPic; + } + + @Override + public String toString() { + return "WxMpMassNewsArticle [" + "thumbMediaId=" + thumbMediaId + ", author=" + author + ", title=" + title + + ", contentSourceUrl=" + contentSourceUrl + ", content=" + content + ", digest=" + digest + + ", showCoverPic=" + showCoverPic + "]"; + } + } + + @Override + public String toString() { + return "WxMpMaterialNews [" + "articles=" + articles + "]"; + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialCountResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialCountResult.java new file mode 100644 index 0000000000..83bb720d4b --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialCountResult.java @@ -0,0 +1,50 @@ +package me.chanjar.weixin.mp.bean.result; + +import java.io.Serializable; + +public class WxMpMaterialCountResult implements Serializable { + + private int voiceCount; + private int videoCount; + private int imageCount; + private int newsCount; + + public int getVoiceCount() { + return voiceCount; + } + + public void setVoiceCount(int voiceCount) { + this.voiceCount = voiceCount; + } + + public int getVideoCount() { + return videoCount; + } + + public void setVideoCount(int videoCount) { + this.videoCount = videoCount; + } + + public int getImageCount() { + return imageCount; + } + + public void setImageCount(int imageCount) { + this.imageCount = imageCount; + } + + public int getNewsCount() { + return newsCount; + } + + public void setNewsCount(int newsCount) { + this.newsCount = newsCount; + } + + @Override + public String toString() { + return "WxMpMaterialCountResult [" + "voiceCount=" + voiceCount + ", videoCount=" + videoCount + + ", imageCount=" + imageCount + ", newsCount=" + newsCount + "]"; + } +} + diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialFileBatchGetResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialFileBatchGetResult.java new file mode 100644 index 0000000000..b47b15a78a --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialFileBatchGetResult.java @@ -0,0 +1,85 @@ +package me.chanjar.weixin.mp.bean.result; + +import java.io.Serializable; +import java.util.Date; +import java.util.List; + +public class WxMpMaterialFileBatchGetResult implements Serializable { + + private int totalCount; + private int itemCount; + private List items; + + public int getTotalCount() { + return totalCount; + } + + public void setTotalCount(int totalCount) { + this.totalCount = totalCount; + } + + public int getItemCount() { + return itemCount; + } + + public void setItemCount(int itemCount) { + this.itemCount = itemCount; + } + + public List getItems() { + return items; + } + + public void setItems(List items) { + this.items = items; + } + + @Override + public String toString() { + return "WxMpMaterialFileBatchGetResult [" + "totalCount=" + totalCount + ", itemCount=" + itemCount + ", items=" + items + "]"; + } + + public static class WxMaterialFileBatchGetNewsItem { + private String mediaId; + private Date updateTime; + private String name; + private String url; + + public String getMediaId() { + return mediaId; + } + + public void setMediaId(String mediaId) { + this.mediaId = mediaId; + } + + public Date getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(Date updateTime) { + this.updateTime = updateTime; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + @Override + public String toString() { + return "WxMaterialFileBatchGetNewsItem [" + "mediaId=" + mediaId + ", updateTime=" + updateTime + ", name=" + name + ", url=" + url + "]"; + } + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialNewsBatchGetResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialNewsBatchGetResult.java new file mode 100644 index 0000000000..2d78ab8cfd --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialNewsBatchGetResult.java @@ -0,0 +1,78 @@ +package me.chanjar.weixin.mp.bean.result; + +import me.chanjar.weixin.mp.bean.WxMpMaterialNews; + +import java.io.Serializable; +import java.util.Date; +import java.util.List; + +public class WxMpMaterialNewsBatchGetResult implements Serializable { + + private int totalCount; + private int itemCount; + private List items; + + public int getTotalCount() { + return totalCount; + } + + public void setTotalCount(int totalCount) { + this.totalCount = totalCount; + } + + public int getItemCount() { + return itemCount; + } + + public void setItemCount(int itemCount) { + this.itemCount = itemCount; + } + + public List getItems() { + return items; + } + + public void setItems(List items) { + this.items = items; + } + + @Override + public String toString() { + return "WxMpMaterialNewsBatchGetResult [" + "totalCount=" + totalCount + ", itemCount=" + itemCount + ", items=" + items + "]"; + } + + public static class WxMaterialNewsBatchGetNewsItem { + private String mediaId; + private Date updateTime; + private WxMpMaterialNews content; + + public String getMediaId() { + return mediaId; + } + + public void setMediaId(String mediaId) { + this.mediaId = mediaId; + } + + public Date getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(Date updateTime) { + this.updateTime = updateTime; + } + + public WxMpMaterialNews getContent() { + return content; + } + + public void setContent(WxMpMaterialNews content) { + this.content = content; + } + + @Override + public String toString() { + return "WxMaterialNewsBatchGetNewsItem [" + "mediaId=" + mediaId + ", updateTime=" + updateTime + ", content=" + content + "]"; + } + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialUploadResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialUploadResult.java new file mode 100644 index 0000000000..2c2bf4d6e0 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialUploadResult.java @@ -0,0 +1,38 @@ +package me.chanjar.weixin.mp.bean.result; + +import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; + +import java.io.Serializable; + +public class WxMpMaterialUploadResult implements Serializable { + + private String mediaId; + private String url; + + public String getMediaId() { + return mediaId; + } + + public void setMediaId(String mediaId) { + this.mediaId = mediaId; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public static WxMpMaterialUploadResult fromJson(String json) { + return WxMpGsonBuilder.create().fromJson(json, WxMpMaterialUploadResult.class); + } + + @Override + public String toString() { + return "WxMpMaterialUploadResult [media_id=" + mediaId + ", url=" + url + "]"; + } + +} + diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialVideoInfoResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialVideoInfoResult.java new file mode 100644 index 0000000000..1650c760e6 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialVideoInfoResult.java @@ -0,0 +1,46 @@ +package me.chanjar.weixin.mp.bean.result; + +import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; + +import java.io.Serializable; + +public class WxMpMaterialVideoInfoResult implements Serializable { + + private String title; + private String description; + private String downUrl; + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getDownUrl() { + return downUrl; + } + + public void setDownUrl(String downUrl) { + this.downUrl = downUrl; + } + + public static WxMpMaterialVideoInfoResult fromJson(String json) { + return WxMpGsonBuilder.create().fromJson(json, WxMpMaterialVideoInfoResult.class); + } + + @Override + public String toString() { + return "WxMpMaterialVideoInfoResult [title=" + title + ", description=" + description + ", downUrl=" + downUrl + "]"; + } + +} 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 new file mode 100644 index 0000000000..4da3417a09 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialDeleteRequestExecutor.java @@ -0,0 +1,47 @@ +package me.chanjar.weixin.mp.util.http; + +import com.google.gson.Gson; +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.Utf8ResponseHandler; +import org.apache.http.HttpHost; +import org.apache.http.client.ClientProtocolException; +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 class MaterialDeleteRequestExecutor implements RequestExecutor { + + + public MaterialDeleteRequestExecutor() { + super(); + } + + public Boolean execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String materialId) throws WxErrorException, ClientProtocolException, 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(new Gson().toJson(params))); + 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; + } + } + +} 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 new file mode 100644 index 0000000000..9cae8268b3 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialNewsInfoRequestExecutor.java @@ -0,0 +1,48 @@ +package me.chanjar.weixin.mp.util.http; + +import com.google.gson.Gson; +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.Utf8ResponseHandler; +import me.chanjar.weixin.mp.bean.WxMpMaterialNews; +import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; +import org.apache.http.HttpHost; +import org.apache.http.client.ClientProtocolException; +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 class MaterialNewsInfoRequestExecutor implements RequestExecutor { + + public MaterialNewsInfoRequestExecutor() { + super(); + } + + public WxMpMaterialNews execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String materialId) throws WxErrorException, ClientProtocolException, 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(new Gson().toJson(params))); + 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); + } + } + +} 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 new file mode 100644 index 0000000000..2d92261461 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialUploadRequestExecutor.java @@ -0,0 +1,58 @@ +package me.chanjar.weixin.mp.util.http; + +import com.google.gson.Gson; +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.Utf8ResponseHandler; +import me.chanjar.weixin.mp.bean.WxMpMaterial; +import me.chanjar.weixin.mp.bean.result.WxMpMaterialUploadResult; +import org.apache.http.HttpHost; +import org.apache.http.client.ClientProtocolException; +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.MultipartEntityBuilder; +import org.apache.http.entity.mime.content.InputStreamBody; +import org.apache.http.impl.client.CloseableHttpClient; + +import java.io.*; +import java.util.Map; + +public class MaterialUploadRequestExecutor implements RequestExecutor { + + public WxMpMaterialUploadResult execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, WxMpMaterial material) throws WxErrorException, ClientProtocolException, IOException { + HttpPost httpPost = new HttpPost(uri); + if (httpProxy != null) { + RequestConfig response = RequestConfig.custom().setProxy(httpProxy).build(); + httpPost.setConfig(response); + } + + if (material != null) { + File file = material.getFile(); + if (file == null || !file.exists()) { + throw new FileNotFoundException(); + } + BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file)); + MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); + multipartEntityBuilder.addPart("media", new InputStreamBody(bufferedInputStream, material.getName())); + Map form = material.getForm(); + if (material.getForm() != null) { + multipartEntityBuilder.addTextBody("description", new Gson().toJson(form)); + } + httpPost.setEntity(multipartEntityBuilder.build()); + httpPost.setHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString()); + } + + 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); + } + } + +} 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 new file mode 100644 index 0000000000..f097eaef54 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialVideoInfoRequestExecutor.java @@ -0,0 +1,47 @@ +package me.chanjar.weixin.mp.util.http; + +import com.google.gson.Gson; +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.Utf8ResponseHandler; +import me.chanjar.weixin.mp.bean.result.WxMpMaterialVideoInfoResult; +import org.apache.http.HttpHost; +import org.apache.http.client.ClientProtocolException; +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 class MaterialVideoInfoRequestExecutor implements RequestExecutor { + + public MaterialVideoInfoRequestExecutor() { + super(); + } + + public WxMpMaterialVideoInfoResult execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String materialId) throws WxErrorException, ClientProtocolException, 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(new Gson().toJson(params))); + 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); + } + } + +} 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 new file mode 100644 index 0000000000..1c7e8639ae --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialVoiceAndImageDownloadRequestExecutor.java @@ -0,0 +1,65 @@ +package me.chanjar.weixin.mp.util.http; + +import com.google.gson.Gson; +import me.chanjar.weixin.common.bean.result.WxError; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.http.InputStreamResponseHandler; +import me.chanjar.weixin.common.util.http.RequestExecutor; +import org.apache.commons.io.IOUtils; +import org.apache.http.HttpHost; +import org.apache.http.client.ClientProtocolException; +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 class MaterialVoiceAndImageDownloadRequestExecutor implements RequestExecutor { + + private File tmpDirFile; + + public MaterialVoiceAndImageDownloadRequestExecutor() { + super(); + } + + public MaterialVoiceAndImageDownloadRequestExecutor(File tmpDirFile) { + super(); + this.tmpDirFile = tmpDirFile; + } + + public InputStream execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String materialId) throws WxErrorException, ClientProtocolException, 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(new Gson().toJson(params))); + 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 = new Gson().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/json/WxMpGsonBuilder.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpGsonBuilder.java index 3516cb9a15..20f8d9d47a 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpGsonBuilder.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpGsonBuilder.java @@ -8,7 +8,7 @@ public class WxMpGsonBuilder { public static final GsonBuilder INSTANCE = new GsonBuilder(); - + static { INSTANCE.disableHtmlEscaping(); INSTANCE.registerTypeAdapter(WxMpCustomMessage.class, new WxMpCustomMessageGsonAdapter()); @@ -27,10 +27,21 @@ public class WxMpGsonBuilder { INSTANCE.registerTypeAdapter(WxMpOAuth2AccessToken.class, new WxMpOAuth2AccessTokenAdapter()); INSTANCE.registerTypeAdapter(WxMpUserSummary.class, new WxMpUserSummaryGsonAdapter()); INSTANCE.registerTypeAdapter(WxMpUserCumulate.class, new WxMpUserCumulateGsonAdapter()); + INSTANCE.registerTypeAdapter(WxMpMaterialUploadResult.class, new WxMpMaterialUploadResultAdapter()); + INSTANCE.registerTypeAdapter(WxMpMaterialVideoInfoResult.class, new WxMpMaterialVideoInfoResultAdapter()); + INSTANCE.registerTypeAdapter(WxMpMassNews.WxMpMassNewsArticle.class, new WxMpMassNewsArticleGsonAdapter()); + INSTANCE.registerTypeAdapter(WxMpMaterialArticleUpdate.class, new WxMpMaterialArticleUpdateGsonAdapter()); + INSTANCE.registerTypeAdapter(WxMpMaterialCountResult.class, new WxMpMaterialCountResultAdapter()); + INSTANCE.registerTypeAdapter(WxMpMaterialNews.class, new WxMpMaterialNewsGsonAdapter()); + INSTANCE.registerTypeAdapter(WxMpMaterialNews.WxMpMaterialNewsArticle.class, new WxMpMaterialNewsArticleGsonAdapter()); + INSTANCE.registerTypeAdapter(WxMpMaterialNewsBatchGetResult.class, new WxMpMaterialNewsBatchGetGsonAdapter()); + INSTANCE.registerTypeAdapter(WxMpMaterialNewsBatchGetResult.WxMaterialNewsBatchGetNewsItem.class, new WxMpMaterialNewsBatchGetGsonItemAdapter()); + INSTANCE.registerTypeAdapter(WxMpMaterialFileBatchGetResult.class, new WxMpMaterialFileBatchGetGsonAdapter()); + INSTANCE.registerTypeAdapter(WxMpMaterialFileBatchGetResult.WxMaterialFileBatchGetNewsItem.class, new WxMpMaterialFileBatchGetGsonItemAdapter()); } - + public static Gson create() { return INSTANCE.create(); } - + } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassNewsArticleGsonAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassNewsArticleGsonAdapter.java new file mode 100644 index 0000000000..32bda06867 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassNewsArticleGsonAdapter.java @@ -0,0 +1,72 @@ +/* + * KINGSTAR MEDIA SOLUTIONS Co.,LTD. Copyright c 2005-2013. All rights reserved. + * + * This source code is the property of KINGSTAR MEDIA SOLUTIONS LTD. It is intended + * only for the use of KINGSTAR MEDIA application development. Reengineering, reproduction + * arose from modification of the original source, or other redistribution of this source + * is not permitted without written permission of the KINGSTAR MEDIA SOLUTIONS LTD. + */ +package me.chanjar.weixin.mp.util.json; + +import com.google.gson.*; +import me.chanjar.weixin.common.util.json.GsonHelper; +import me.chanjar.weixin.mp.bean.WxMpMassNews; + +import java.lang.reflect.Type; + +public class WxMpMassNewsArticleGsonAdapter implements JsonSerializer, JsonDeserializer { + + public JsonElement serialize(WxMpMassNews.WxMpMassNewsArticle article, Type typeOfSrc, JsonSerializationContext context) { + JsonObject articleJson = new JsonObject(); + + articleJson.addProperty("thumb_media_id", article.getThumbMediaId()); + articleJson.addProperty("title", article.getTitle()); + articleJson.addProperty("content", article.getContent()); + if (null != article.getAuthor()) { + articleJson.addProperty("author", article.getAuthor()); + } + if (null != article.getContentSourceUrl()) { + articleJson.addProperty("content_source_url", article.getContentSourceUrl()); + } + if (null != article.getDigest()) { + articleJson.addProperty("digest", article.getDigest()); + } + articleJson.addProperty("show_cover_pic", article.isShowCoverPic() ? "1" : "0"); + return articleJson; + } + + public WxMpMassNews.WxMpMassNewsArticle deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { + JsonObject articleInfo = jsonElement.getAsJsonObject(); + WxMpMassNews.WxMpMassNewsArticle article = new WxMpMassNews.WxMpMassNewsArticle(); + + JsonElement title = articleInfo.get("title"); + if (title != null && !title.isJsonNull()) { + article.setTitle(GsonHelper.getAsString(title)); + } + JsonElement content = articleInfo.get("content"); + if (content != null && !content.isJsonNull()) { + article.setContent(GsonHelper.getAsString(content)); + } + JsonElement contentSourceUrl = articleInfo.get("content_source_url"); + if (contentSourceUrl != null && !contentSourceUrl.isJsonNull()) { + article.setContentSourceUrl(GsonHelper.getAsString(contentSourceUrl)); + } + JsonElement author = articleInfo.get("author"); + if (author != null && !author.isJsonNull()) { + article.setAuthor(GsonHelper.getAsString(author)); + } + JsonElement digest = articleInfo.get("digest"); + if (digest != null && !digest.isJsonNull()) { + article.setDigest(GsonHelper.getAsString(digest)); + } + JsonElement thumbMediaId = articleInfo.get("thumb_media_id"); + if (thumbMediaId != null && !thumbMediaId.isJsonNull()) { + article.setThumbMediaId(GsonHelper.getAsString(thumbMediaId)); + } + JsonElement showCoverPic = articleInfo.get("show_cover_pic"); + if (showCoverPic != null && !showCoverPic.isJsonNull()) { + article.setShowCoverPic(GsonHelper.getAsBoolean(showCoverPic)); + } + return article; + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassNewsGsonAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassNewsGsonAdapter.java index 1719b75ac6..2a5c228308 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassNewsGsonAdapter.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassNewsGsonAdapter.java @@ -13,33 +13,32 @@ import java.lang.reflect.Type; -public class WxMpMassNewsGsonAdapter implements JsonSerializer { +public class WxMpMassNewsGsonAdapter implements JsonSerializer, JsonDeserializer { public JsonElement serialize(WxMpMassNews message, Type typeOfSrc, JsonSerializationContext context) { JsonObject newsJson = new JsonObject(); - + JsonArray articleJsonArray = new JsonArray(); for (WxMpMassNews.WxMpMassNewsArticle article : message.getArticles()) { - JsonObject articleJson = new JsonObject(); - articleJson.addProperty("thumb_media_id", article.getThumbMediaId()); - articleJson.addProperty("title", article.getTitle()); - articleJson.addProperty("content", article.getContent()); - - if (null != article.getAuthor()) { - articleJson.addProperty("author", article.getAuthor()); - } - if (null != article.getContentSourceUrl()) { - articleJson.addProperty("content_source_url", article.getContentSourceUrl()); - } - if (null != article.getDigest()) { - articleJson.addProperty("digest", article.getDigest()); - } - articleJson.addProperty("show_cover_pic", article.isShowCoverPic() ? "1" : "0"); + JsonObject articleJson = WxMpGsonBuilder.create().toJsonTree(article, WxMpMassNews.WxMpMassNewsArticle.class).getAsJsonObject(); articleJsonArray.add(articleJson); } newsJson.add("articles", articleJsonArray); - + return newsJson; } + public WxMpMassNews deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { + WxMpMassNews wxMpMassNews = new WxMpMassNews(); + JsonObject json = jsonElement.getAsJsonObject(); + if (json.get("media_id") != null && !json.get("media_id").isJsonNull()) { + JsonArray articles = json.getAsJsonArray("articles"); + for (JsonElement article1 : articles) { + JsonObject articleInfo = article1.getAsJsonObject(); + WxMpMassNews.WxMpMassNewsArticle article = WxMpGsonBuilder.create().fromJson(articleInfo, WxMpMassNews.WxMpMassNewsArticle.class); + wxMpMassNews.addArticle(article); + } + } + return wxMpMassNews; + } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialArticleUpdateGsonAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialArticleUpdateGsonAdapter.java new file mode 100644 index 0000000000..93391732e9 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialArticleUpdateGsonAdapter.java @@ -0,0 +1,30 @@ +/* + * KINGSTAR MEDIA SOLUTIONS Co.,LTD. Copyright c 2005-2013. All rights reserved. + * + * This source code is the property of KINGSTAR MEDIA SOLUTIONS LTD. It is intended + * only for the use of KINGSTAR MEDIA application development. Reengineering, reproduction + * arose from modification of the original source, or other redistribution of this source + * is not permitted without written permission of the KINGSTAR MEDIA SOLUTIONS LTD. + */ +package me.chanjar.weixin.mp.util.json; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import me.chanjar.weixin.mp.bean.WxMpMaterialArticleUpdate; +import me.chanjar.weixin.mp.bean.WxMpMaterialNews; + +import java.lang.reflect.Type; + +public class WxMpMaterialArticleUpdateGsonAdapter implements JsonSerializer { + + public JsonElement serialize(WxMpMaterialArticleUpdate wxMpMaterialArticleUpdate, Type typeOfSrc, JsonSerializationContext context) { + JsonObject articleUpdateJson = new JsonObject(); + articleUpdateJson.addProperty("media_id", wxMpMaterialArticleUpdate.getMediaId()); + articleUpdateJson.addProperty("index", wxMpMaterialArticleUpdate.getIndex()); + articleUpdateJson.add("articles", WxMpGsonBuilder.create().toJsonTree(wxMpMaterialArticleUpdate.getArticles(), WxMpMaterialNews.WxMpMaterialNewsArticle.class)); + return articleUpdateJson; + } + +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialCountResultAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialCountResultAdapter.java new file mode 100644 index 0000000000..0178a36870 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialCountResultAdapter.java @@ -0,0 +1,41 @@ +/* + * KINGSTAR MEDIA SOLUTIONS Co.,LTD. Copyright c 2005-2013. All rights reserved. + * + * This source code is the property of KINGSTAR MEDIA SOLUTIONS LTD. It is intended + * only for the use of KINGSTAR MEDIA application development. Reengineering, reproduction + * arose from modification of the original source, or other redistribution of this source + * is not permitted without written permission of the KINGSTAR MEDIA SOLUTIONS LTD. + */ +package me.chanjar.weixin.mp.util.json; + +import com.google.gson.*; +import me.chanjar.weixin.common.util.json.GsonHelper; +import me.chanjar.weixin.mp.bean.result.WxMpMaterialCountResult; + +import java.lang.reflect.Type; + +/** + * @author codepiano + */ +public class WxMpMaterialCountResultAdapter implements JsonDeserializer { + + public WxMpMaterialCountResult deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + WxMpMaterialCountResult countResult = new WxMpMaterialCountResult(); + JsonObject materialCountResultJsonObject = json.getAsJsonObject(); + + if (materialCountResultJsonObject.get("voice_count") != null && !materialCountResultJsonObject.get("voice_count").isJsonNull()) { + countResult.setVoiceCount(GsonHelper.getAsInteger(materialCountResultJsonObject.get("voice_count"))); + } + if (materialCountResultJsonObject.get("video_count") != null && !materialCountResultJsonObject.get("video_count").isJsonNull()) { + countResult.setVideoCount(GsonHelper.getAsInteger(materialCountResultJsonObject.get("video_count"))); + } + if (materialCountResultJsonObject.get("image_count") != null && !materialCountResultJsonObject.get("image_count").isJsonNull()) { + countResult.setImageCount(GsonHelper.getAsInteger(materialCountResultJsonObject.get("image_count"))); + } + if (materialCountResultJsonObject.get("news_count") != null && !materialCountResultJsonObject.get("news_count").isJsonNull()) { + countResult.setNewsCount(GsonHelper.getAsInteger(materialCountResultJsonObject.get("news_count"))); + } + return countResult; + } + +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialFileBatchGetGsonAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialFileBatchGetGsonAdapter.java new file mode 100644 index 0000000000..5483068f63 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialFileBatchGetGsonAdapter.java @@ -0,0 +1,41 @@ +/* + * KINGSTAR MEDIA SOLUTIONS Co.,LTD. Copyright c 2005-2013. All rights reserved. + * + * This source code is the property of KINGSTAR MEDIA SOLUTIONS LTD. It is intended + * only for the use of KINGSTAR MEDIA application development. Reengineering, reproduction + * arose from modification of the original source, or other redistribution of this source + * is not permitted without written permission of the KINGSTAR MEDIA SOLUTIONS LTD. + */ +package me.chanjar.weixin.mp.util.json; + +import com.google.gson.*; +import me.chanjar.weixin.common.util.json.GsonHelper; +import me.chanjar.weixin.mp.bean.result.WxMpMaterialFileBatchGetResult; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.List; + +public class WxMpMaterialFileBatchGetGsonAdapter implements JsonDeserializer { + + public WxMpMaterialFileBatchGetResult deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { + WxMpMaterialFileBatchGetResult wxMpMaterialFileBatchGetResult = new WxMpMaterialFileBatchGetResult(); + JsonObject json = jsonElement.getAsJsonObject(); + if (json.get("total_count") != null && !json.get("total_count").isJsonNull()) { + wxMpMaterialFileBatchGetResult.setTotalCount(GsonHelper.getAsInteger(json.get("total_count"))); + } + if (json.get("item_count") != null && !json.get("item_count").isJsonNull()) { + wxMpMaterialFileBatchGetResult.setItemCount(GsonHelper.getAsInteger(json.get("item_count"))); + } + if (json.get("item") != null && !json.get("item").isJsonNull()) { + JsonArray item = json.getAsJsonArray("item"); + List items = new ArrayList(); + for (JsonElement anItem : item) { + JsonObject articleInfo = anItem.getAsJsonObject(); + items.add(WxMpGsonBuilder.create().fromJson(articleInfo, WxMpMaterialFileBatchGetResult.WxMaterialFileBatchGetNewsItem.class)); + } + wxMpMaterialFileBatchGetResult.setItems(items); + } + return wxMpMaterialFileBatchGetResult; + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialFileBatchGetGsonItemAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialFileBatchGetGsonItemAdapter.java new file mode 100644 index 0000000000..5be696ad3a --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialFileBatchGetGsonItemAdapter.java @@ -0,0 +1,37 @@ +/* + * KINGSTAR MEDIA SOLUTIONS Co.,LTD. Copyright c 2005-2013. All rights reserved. + * + * This source code is the property of KINGSTAR MEDIA SOLUTIONS LTD. It is intended + * only for the use of KINGSTAR MEDIA application development. Reengineering, reproduction + * arose from modification of the original source, or other redistribution of this source + * is not permitted without written permission of the KINGSTAR MEDIA SOLUTIONS LTD. + */ +package me.chanjar.weixin.mp.util.json; + +import com.google.gson.*; +import me.chanjar.weixin.common.util.json.GsonHelper; +import me.chanjar.weixin.mp.bean.result.WxMpMaterialFileBatchGetResult; + +import java.lang.reflect.Type; +import java.util.Date; + +public class WxMpMaterialFileBatchGetGsonItemAdapter implements JsonDeserializer { + + public WxMpMaterialFileBatchGetResult.WxMaterialFileBatchGetNewsItem deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { + WxMpMaterialFileBatchGetResult.WxMaterialFileBatchGetNewsItem wxMaterialFileBatchGetNewsItem = new WxMpMaterialFileBatchGetResult.WxMaterialFileBatchGetNewsItem(); + JsonObject json = jsonElement.getAsJsonObject(); + if (json.get("media_id") != null && !json.get("media_id").isJsonNull()) { + wxMaterialFileBatchGetNewsItem.setMediaId(GsonHelper.getAsString(json.get("media_id"))); + } + if (json.get("update_time") != null && !json.get("update_time").isJsonNull()) { + wxMaterialFileBatchGetNewsItem.setUpdateTime(new Date(1000 * GsonHelper.getAsLong(json.get("update_time")))); + } + if (json.get("name") != null && !json.get("name").isJsonNull()) { + wxMaterialFileBatchGetNewsItem.setName(GsonHelper.getAsString(json.get("name"))); + } + if (json.get("url") != null && !json.get("url").isJsonNull()) { + wxMaterialFileBatchGetNewsItem.setUrl(GsonHelper.getAsString(json.get("url"))); + } + return wxMaterialFileBatchGetNewsItem; + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialNewsArticleGsonAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialNewsArticleGsonAdapter.java new file mode 100644 index 0000000000..4f0e2e6d49 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialNewsArticleGsonAdapter.java @@ -0,0 +1,72 @@ +/* + * KINGSTAR MEDIA SOLUTIONS Co.,LTD. Copyright c 2005-2013. All rights reserved. + * + * This source code is the property of KINGSTAR MEDIA SOLUTIONS LTD. It is intended + * only for the use of KINGSTAR MEDIA application development. Reengineering, reproduction + * arose from modification of the original source, or other redistribution of this source + * is not permitted without written permission of the KINGSTAR MEDIA SOLUTIONS LTD. + */ +package me.chanjar.weixin.mp.util.json; + +import com.google.gson.*; +import me.chanjar.weixin.common.util.json.GsonHelper; +import me.chanjar.weixin.mp.bean.WxMpMaterialNews; + +import java.lang.reflect.Type; + +public class WxMpMaterialNewsArticleGsonAdapter implements JsonSerializer, JsonDeserializer { + + public JsonElement serialize(WxMpMaterialNews.WxMpMaterialNewsArticle article, Type typeOfSrc, JsonSerializationContext context) { + JsonObject articleJson = new JsonObject(); + + articleJson.addProperty("thumb_media_id", article.getThumbMediaId()); + articleJson.addProperty("title", article.getTitle()); + articleJson.addProperty("content", article.getContent()); + if (null != article.getAuthor()) { + articleJson.addProperty("author", article.getAuthor()); + } + if (null != article.getContentSourceUrl()) { + articleJson.addProperty("content_source_url", article.getContentSourceUrl()); + } + if (null != article.getDigest()) { + articleJson.addProperty("digest", article.getDigest()); + } + articleJson.addProperty("show_cover_pic", article.isShowCoverPic() ? "1" : "0"); + return articleJson; + } + + public WxMpMaterialNews.WxMpMaterialNewsArticle deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { + JsonObject articleInfo = jsonElement.getAsJsonObject(); + WxMpMaterialNews.WxMpMaterialNewsArticle article = new WxMpMaterialNews.WxMpMaterialNewsArticle(); + + JsonElement title = articleInfo.get("title"); + if (title != null && !title.isJsonNull()) { + article.setTitle(GsonHelper.getAsString(title)); + } + JsonElement content = articleInfo.get("content"); + if (content != null && !content.isJsonNull()) { + article.setContent(GsonHelper.getAsString(content)); + } + JsonElement contentSourceUrl = articleInfo.get("content_source_url"); + if (contentSourceUrl != null && !contentSourceUrl.isJsonNull()) { + article.setContentSourceUrl(GsonHelper.getAsString(contentSourceUrl)); + } + JsonElement author = articleInfo.get("author"); + if (author != null && !author.isJsonNull()) { + article.setAuthor(GsonHelper.getAsString(author)); + } + JsonElement digest = articleInfo.get("digest"); + if (digest != null && !digest.isJsonNull()) { + article.setDigest(GsonHelper.getAsString(digest)); + } + JsonElement thumbMediaId = articleInfo.get("thumb_media_id"); + if (thumbMediaId != null && !thumbMediaId.isJsonNull()) { + article.setThumbMediaId(GsonHelper.getAsString(thumbMediaId)); + } + JsonElement showCoverPic = articleInfo.get("show_cover_pic"); + if (showCoverPic != null && !showCoverPic.isJsonNull()) { + article.setShowCoverPic(GsonHelper.getAsBoolean(showCoverPic)); + } + return article; + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialNewsBatchGetGsonAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialNewsBatchGetGsonAdapter.java new file mode 100644 index 0000000000..e78a158656 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialNewsBatchGetGsonAdapter.java @@ -0,0 +1,41 @@ +/* + * KINGSTAR MEDIA SOLUTIONS Co.,LTD. Copyright c 2005-2013. All rights reserved. + * + * This source code is the property of KINGSTAR MEDIA SOLUTIONS LTD. It is intended + * only for the use of KINGSTAR MEDIA application development. Reengineering, reproduction + * arose from modification of the original source, or other redistribution of this source + * is not permitted without written permission of the KINGSTAR MEDIA SOLUTIONS LTD. + */ +package me.chanjar.weixin.mp.util.json; + +import com.google.gson.*; +import me.chanjar.weixin.common.util.json.GsonHelper; +import me.chanjar.weixin.mp.bean.result.WxMpMaterialNewsBatchGetResult; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.List; + +public class WxMpMaterialNewsBatchGetGsonAdapter implements JsonDeserializer { + + public WxMpMaterialNewsBatchGetResult deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { + WxMpMaterialNewsBatchGetResult wxMpMaterialNewsBatchGetResult = new WxMpMaterialNewsBatchGetResult(); + JsonObject json = jsonElement.getAsJsonObject(); + if (json.get("total_count") != null && !json.get("total_count").isJsonNull()) { + wxMpMaterialNewsBatchGetResult.setTotalCount(GsonHelper.getAsInteger(json.get("total_count"))); + } + if (json.get("item_count") != null && !json.get("item_count").isJsonNull()) { + wxMpMaterialNewsBatchGetResult.setItemCount(GsonHelper.getAsInteger(json.get("item_count"))); + } + if (json.get("item") != null && !json.get("item").isJsonNull()) { + JsonArray item = json.getAsJsonArray("item"); + List items = new ArrayList(); + for (JsonElement anItem : item) { + JsonObject articleInfo = anItem.getAsJsonObject(); + items.add(WxMpGsonBuilder.create().fromJson(articleInfo, WxMpMaterialNewsBatchGetResult.WxMaterialNewsBatchGetNewsItem.class)); + } + wxMpMaterialNewsBatchGetResult.setItems(items); + } + return wxMpMaterialNewsBatchGetResult; + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialNewsBatchGetGsonItemAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialNewsBatchGetGsonItemAdapter.java new file mode 100644 index 0000000000..8df7c20d63 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialNewsBatchGetGsonItemAdapter.java @@ -0,0 +1,36 @@ +/* + * KINGSTAR MEDIA SOLUTIONS Co.,LTD. Copyright c 2005-2013. All rights reserved. + * + * This source code is the property of KINGSTAR MEDIA SOLUTIONS LTD. It is intended + * only for the use of KINGSTAR MEDIA application development. Reengineering, reproduction + * arose from modification of the original source, or other redistribution of this source + * is not permitted without written permission of the KINGSTAR MEDIA SOLUTIONS LTD. + */ +package me.chanjar.weixin.mp.util.json; + +import com.google.gson.*; +import me.chanjar.weixin.common.util.json.GsonHelper; +import me.chanjar.weixin.mp.bean.WxMpMaterialNews; +import me.chanjar.weixin.mp.bean.result.WxMpMaterialNewsBatchGetResult; + +import java.lang.reflect.Type; +import java.util.Date; + +public class WxMpMaterialNewsBatchGetGsonItemAdapter implements JsonDeserializer { + + public WxMpMaterialNewsBatchGetResult.WxMaterialNewsBatchGetNewsItem deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { + WxMpMaterialNewsBatchGetResult.WxMaterialNewsBatchGetNewsItem wxMaterialNewsBatchGetNewsItem = new WxMpMaterialNewsBatchGetResult.WxMaterialNewsBatchGetNewsItem(); + JsonObject json = jsonElement.getAsJsonObject(); + if (json.get("media_id") != null && !json.get("media_id").isJsonNull()) { + wxMaterialNewsBatchGetNewsItem.setMediaId(GsonHelper.getAsString(json.get("media_id"))); + } + if (json.get("update_time") != null && !json.get("update_time").isJsonNull()) { + wxMaterialNewsBatchGetNewsItem.setUpdateTime(new Date(1000 * GsonHelper.getAsLong(json.get("update_time")))); + } + if (json.get("content") != null && !json.get("content").isJsonNull()) { + JsonObject newsItem = json.getAsJsonObject("content"); + wxMaterialNewsBatchGetNewsItem.setContent(WxMpGsonBuilder.create().fromJson(newsItem, WxMpMaterialNews.class)); + } + return wxMaterialNewsBatchGetNewsItem; + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialNewsGsonAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialNewsGsonAdapter.java new file mode 100644 index 0000000000..93c002a48e --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialNewsGsonAdapter.java @@ -0,0 +1,44 @@ +/* + * KINGSTAR MEDIA SOLUTIONS Co.,LTD. Copyright c 2005-2013. All rights reserved. + * + * This source code is the property of KINGSTAR MEDIA SOLUTIONS LTD. It is intended + * only for the use of KINGSTAR MEDIA application development. Reengineering, reproduction + * arose from modification of the original source, or other redistribution of this source + * is not permitted without written permission of the KINGSTAR MEDIA SOLUTIONS LTD. + */ +package me.chanjar.weixin.mp.util.json; + +import com.google.gson.*; +import me.chanjar.weixin.mp.bean.WxMpMaterialNews; + +import java.lang.reflect.Type; + +public class WxMpMaterialNewsGsonAdapter implements JsonSerializer, JsonDeserializer { + + public JsonElement serialize(WxMpMaterialNews wxMpMaterialNews, Type typeOfSrc, JsonSerializationContext context) { + JsonObject newsJson = new JsonObject(); + + JsonArray articleJsonArray = new JsonArray(); + for (WxMpMaterialNews.WxMpMaterialNewsArticle article : wxMpMaterialNews.getArticles()) { + JsonObject articleJson = WxMpGsonBuilder.create().toJsonTree(article, WxMpMaterialNews.WxMpMaterialNewsArticle.class).getAsJsonObject(); + articleJsonArray.add(articleJson); + } + newsJson.add("articles", articleJsonArray); + + return newsJson; + } + + public WxMpMaterialNews deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { + WxMpMaterialNews wxMpMaterialNews = new WxMpMaterialNews(); + JsonObject json = jsonElement.getAsJsonObject(); + if (json.get("news_item") != null && !json.get("news_item").isJsonNull()) { + JsonArray articles = json.getAsJsonArray("news_item"); + for (JsonElement article1 : articles) { + JsonObject articleInfo = article1.getAsJsonObject(); + WxMpMaterialNews.WxMpMaterialNewsArticle article = WxMpGsonBuilder.create().fromJson(articleInfo, WxMpMaterialNews.WxMpMaterialNewsArticle.class); + wxMpMaterialNews.addArticle(article); + } + } + return wxMpMaterialNews; + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialUploadResultAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialUploadResultAdapter.java new file mode 100644 index 0000000000..d5cd728cdd --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialUploadResultAdapter.java @@ -0,0 +1,35 @@ +/* + * KINGSTAR MEDIA SOLUTIONS Co.,LTD. Copyright c 2005-2013. All rights reserved. + * + * This source code is the property of KINGSTAR MEDIA SOLUTIONS LTD. It is intended + * only for the use of KINGSTAR MEDIA application development. Reengineering, reproduction + * arose from modification of the original source, or other redistribution of this source + * is not permitted without written permission of the KINGSTAR MEDIA SOLUTIONS LTD. + */ +package me.chanjar.weixin.mp.util.json; + +import com.google.gson.*; +import me.chanjar.weixin.common.util.json.GsonHelper; +import me.chanjar.weixin.mp.bean.result.WxMpMaterialUploadResult; + +import java.lang.reflect.Type; + +/** + * @author codepiano + */ +public class WxMpMaterialUploadResultAdapter implements JsonDeserializer { + + public WxMpMaterialUploadResult deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + WxMpMaterialUploadResult uploadResult = new WxMpMaterialUploadResult(); + JsonObject uploadResultJsonObject = json.getAsJsonObject(); + + if (uploadResultJsonObject.get("url") != null && !uploadResultJsonObject.get("url").isJsonNull()) { + uploadResult.setUrl(GsonHelper.getAsString(uploadResultJsonObject.get("url"))); + } + if (uploadResultJsonObject.get("media_id") != null && !uploadResultJsonObject.get("media_id").isJsonNull()) { + uploadResult.setMediaId(GsonHelper.getAsString(uploadResultJsonObject.get("media_id"))); + } + return uploadResult; + } + +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialVideoInfoResultAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialVideoInfoResultAdapter.java new file mode 100644 index 0000000000..6f4ce92862 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialVideoInfoResultAdapter.java @@ -0,0 +1,30 @@ +package me.chanjar.weixin.mp.util.json; + +import com.google.gson.*; +import me.chanjar.weixin.common.util.json.GsonHelper; +import me.chanjar.weixin.mp.bean.result.WxMpMaterialVideoInfoResult; + +import java.lang.reflect.Type; + +/** + * @author codepiano + */ +public class WxMpMaterialVideoInfoResultAdapter implements JsonDeserializer { + + public WxMpMaterialVideoInfoResult deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + WxMpMaterialVideoInfoResult uploadResult = new WxMpMaterialVideoInfoResult(); + JsonObject uploadResultJsonObject = json.getAsJsonObject(); + + if (uploadResultJsonObject.get("title") != null && !uploadResultJsonObject.get("title").isJsonNull()) { + uploadResult.setTitle(GsonHelper.getAsString(uploadResultJsonObject.get("title"))); + } + if (uploadResultJsonObject.get("description") != null && !uploadResultJsonObject.get("description").isJsonNull()) { + uploadResult.setDescription(GsonHelper.getAsString(uploadResultJsonObject.get("description"))); + } + if (uploadResultJsonObject.get("down_url") != null && !uploadResultJsonObject.get("down_url").isJsonNull()) { + uploadResult.setDownUrl(GsonHelper.getAsString(uploadResultJsonObject.get("down_url"))); + } + return uploadResult; + } + +} diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxMpMaterialAPITest.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxMpMaterialAPITest.java new file mode 100644 index 0000000000..bddc864f11 --- /dev/null +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/WxMpMaterialAPITest.java @@ -0,0 +1,237 @@ +package me.chanjar.weixin.mp.api; + +import com.google.inject.Inject; +import me.chanjar.weixin.common.api.WxConsts; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.common.util.fs.FileUtils; +import me.chanjar.weixin.mp.bean.WxMpMaterial; +import me.chanjar.weixin.mp.bean.WxMpMaterialArticleUpdate; +import me.chanjar.weixin.mp.bean.WxMpMaterialNews; +import me.chanjar.weixin.mp.bean.result.*; +import org.apache.commons.io.IOUtils; +import org.testng.Assert; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Guice; +import org.testng.annotations.Test; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.*; + +/** + * 测试多媒体文件上传下载 + * + * @author codepiano + */ +@Test(groups = "materialAPI") +@Guice(modules = ApiTestModule.class) +public class WxMpMaterialAPITest { + + @Inject + protected WxMpServiceImpl wxService; + + private Map> media_ids = new LinkedHashMap>(); + // 缩略图的id,测试上传图文使用 + private String thumbMediaId = ""; + // 单图文消息media_id + private String singleNewsMediaId = ""; + // 多图文消息media_id + private String multiNewsMediaId = ""; + // 先查询保存测试开始前永久素材数据 + private WxMpMaterialCountResult wxMaterialCountResultBeforeTest; + + @Test(dataProvider = "uploadMaterial") + public void testUploadMaterial(String mediaType, String fileType, String fileName) throws WxErrorException, IOException { + if (wxMaterialCountResultBeforeTest == null) { + wxMaterialCountResultBeforeTest = wxService.materialCount(); + } + InputStream inputStream = ClassLoader.getSystemResourceAsStream(fileName); + File tempFile = FileUtils.createTmpFile(inputStream, UUID.randomUUID().toString(), fileType); + WxMpMaterial wxMaterial = new WxMpMaterial(); + wxMaterial.setFile(tempFile); + wxMaterial.setName(fileName); + if (WxConsts.MEDIA_VIDEO.equals(mediaType)) { + wxMaterial.setVideoTitle("title"); + wxMaterial.setVideoIntroduction("test video description"); + } + WxMpMaterialUploadResult res = wxService.materialFileUpload(mediaType, wxMaterial); + Assert.assertNotNull(res.getMediaId()); + if (WxConsts.MEDIA_IMAGE.equals(mediaType) || WxConsts.MEDIA_THUMB.equals(mediaType)) { + Assert.assertNotNull(res.getUrl()); + } + if (WxConsts.MEDIA_THUMB.equals(mediaType)) { + thumbMediaId = res.getMediaId(); + } + + Map materialInfo = new HashMap(); + materialInfo.put("media_id", res.getMediaId()); + materialInfo.put("length", tempFile.length()); + materialInfo.put("filename", tempFile.getName()); + media_ids.put(res.getMediaId(), materialInfo); + } + + @Test(dependsOnMethods = {"testUploadMaterial"}) + public void testAddNews() throws WxErrorException { + + // 单图文消息 + WxMpMaterialNews wxMpMaterialNewsSingle = new WxMpMaterialNews(); + WxMpMaterialNews.WxMpMaterialNewsArticle mpMaterialNewsArticleSingle = new WxMpMaterialNews.WxMpMaterialNewsArticle(); + mpMaterialNewsArticleSingle.setAuthor("author"); + mpMaterialNewsArticleSingle.setThumbMediaId(thumbMediaId); + mpMaterialNewsArticleSingle.setTitle("single title"); + mpMaterialNewsArticleSingle.setContent("single content"); + mpMaterialNewsArticleSingle.setContentSourceUrl("content url"); + mpMaterialNewsArticleSingle.setShowCoverPic(true); + mpMaterialNewsArticleSingle.setDigest("single news"); + wxMpMaterialNewsSingle.addArticle(mpMaterialNewsArticleSingle); + + // 多图文消息 + WxMpMaterialNews wxMpMaterialNewsMultiple = new WxMpMaterialNews(); + WxMpMaterialNews.WxMpMaterialNewsArticle wxMpMaterialNewsArticleMutiple1 = new WxMpMaterialNews.WxMpMaterialNewsArticle(); + wxMpMaterialNewsArticleMutiple1.setAuthor("author1"); + wxMpMaterialNewsArticleMutiple1.setThumbMediaId(thumbMediaId); + wxMpMaterialNewsArticleMutiple1.setTitle("multi title1"); + wxMpMaterialNewsArticleMutiple1.setContent("content 1"); + wxMpMaterialNewsArticleMutiple1.setContentSourceUrl("content url"); + wxMpMaterialNewsArticleMutiple1.setShowCoverPic(true); + wxMpMaterialNewsArticleMutiple1.setDigest(""); + + WxMpMaterialNews.WxMpMaterialNewsArticle wxMpMaterialNewsArticleMultiple2 = new WxMpMaterialNews.WxMpMaterialNewsArticle(); + wxMpMaterialNewsArticleMultiple2.setAuthor("author2"); + wxMpMaterialNewsArticleMultiple2.setThumbMediaId(thumbMediaId); + wxMpMaterialNewsArticleMultiple2.setTitle("multi title2"); + wxMpMaterialNewsArticleMultiple2.setContent("content 2"); + wxMpMaterialNewsArticleMultiple2.setContentSourceUrl("content url"); + wxMpMaterialNewsArticleMultiple2.setShowCoverPic(true); + wxMpMaterialNewsArticleMultiple2.setDigest(""); + + wxMpMaterialNewsMultiple.addArticle(wxMpMaterialNewsArticleMutiple1); + wxMpMaterialNewsMultiple.addArticle(wxMpMaterialNewsArticleMultiple2); + + WxMpMaterialUploadResult resSingle = wxService.materialNewsUpload(wxMpMaterialNewsSingle); + singleNewsMediaId = resSingle.getMediaId(); + WxMpMaterialUploadResult resMulti = wxService.materialNewsUpload(wxMpMaterialNewsMultiple); + multiNewsMediaId = resMulti.getMediaId(); + } + + @Test(dependsOnMethods = {"testAddNews"}) + public void testMaterialCount() throws WxErrorException { + WxMpMaterialCountResult wxMaterialCountResult = wxService.materialCount(); + // 测试上传过程中添加了一个音频,一个视频,两个图片,两个图文消息 + Assert.assertEquals(wxMaterialCountResultBeforeTest.getVoiceCount() + 1, wxMaterialCountResult.getVoiceCount()); + Assert.assertEquals(wxMaterialCountResultBeforeTest.getVideoCount() + 1, wxMaterialCountResult.getVideoCount()); + Assert.assertEquals(wxMaterialCountResultBeforeTest.getImageCount() + 2, wxMaterialCountResult.getImageCount()); + Assert.assertEquals(wxMaterialCountResultBeforeTest.getNewsCount() + 2, wxMaterialCountResult.getNewsCount()); + } + + + @DataProvider + public Object[][] uploadMaterial() { + return new Object[][]{ + new Object[]{WxConsts.MEDIA_IMAGE, WxConsts.FILE_JPG, "mm.jpeg"}, + new Object[]{WxConsts.MEDIA_VOICE, WxConsts.FILE_MP3, "mm.mp3"}, + new Object[]{WxConsts.MEDIA_VIDEO, WxConsts.FILE_MP4, "mm.mp4"}, + new Object[]{WxConsts.MEDIA_THUMB, WxConsts.FILE_JPG, "mm.jpeg"} + }; + } + + @Test(dependsOnMethods = {"testMaterialCount"}, dataProvider = "downloadMaterial") + public void testDownloadMaterial(String media_id) throws WxErrorException, IOException { + Map materialInfo = media_ids.get(media_id); + Assert.assertNotNull(materialInfo); + String filename = materialInfo.get("filename").toString(); + if (filename.endsWith(".mp3") || filename.endsWith(".jpeg")) { + InputStream inputStream = wxService.materialImageOrVoiceDownload(media_id); + Assert.assertNotNull(inputStream); + IOUtils.closeQuietly(inputStream); + } + if (filename.endsWith("mp4")) { + WxMpMaterialVideoInfoResult wxMaterialVideoInfoResult = wxService.materialVideoInfo(media_id); + Assert.assertNotNull(wxMaterialVideoInfoResult); + Assert.assertNotNull(wxMaterialVideoInfoResult.getDownUrl()); + } + } + + @Test(dependsOnMethods = {"testAddNews"}) + public void testGetNewsInfo() throws WxErrorException { + WxMpMaterialNews wxMpMaterialNewsSingle = wxService.materialNewsInfo(singleNewsMediaId); + WxMpMaterialNews wxMpMaterialNewsMultiple = wxService.materialNewsInfo(multiNewsMediaId); + Assert.assertNotNull(wxMpMaterialNewsSingle); + Assert.assertNotNull(wxMpMaterialNewsMultiple); + } + + @Test(dependsOnMethods = {"testGetNewsInfo"}) + public void testUpdateNewsInfo() throws WxErrorException { + WxMpMaterialNews wxMpMaterialNewsSingle = wxService.materialNewsInfo(singleNewsMediaId); + Assert.assertNotNull(wxMpMaterialNewsSingle); + WxMpMaterialArticleUpdate wxMpMaterialArticleUpdateSingle = new WxMpMaterialArticleUpdate(); + WxMpMaterialNews.WxMpMaterialNewsArticle articleSingle = wxMpMaterialNewsSingle.getArticles().get(0); + articleSingle.setContent("content single update"); + wxMpMaterialArticleUpdateSingle.setMediaId(singleNewsMediaId); + wxMpMaterialArticleUpdateSingle.setArticles(articleSingle); + wxMpMaterialArticleUpdateSingle.setIndex(0); + boolean resultSingle = wxService.materialNewsUpdate(wxMpMaterialArticleUpdateSingle); + Assert.assertTrue(resultSingle); + wxMpMaterialNewsSingle = wxService.materialNewsInfo(singleNewsMediaId); + Assert.assertNotNull(wxMpMaterialNewsSingle); + Assert.assertEquals("content single update", wxMpMaterialNewsSingle.getArticles().get(0).getContent()); + + WxMpMaterialNews wxMpMaterialNewsMultiple = wxService.materialNewsInfo(multiNewsMediaId); + Assert.assertNotNull(wxMpMaterialNewsMultiple); + WxMpMaterialArticleUpdate wxMpMaterialArticleUpdateMulti = new WxMpMaterialArticleUpdate(); + WxMpMaterialNews.WxMpMaterialNewsArticle articleMulti = wxMpMaterialNewsMultiple.getArticles().get(1); + articleMulti.setContent("content 2 update"); + wxMpMaterialArticleUpdateMulti.setMediaId(multiNewsMediaId); + wxMpMaterialArticleUpdateMulti.setArticles(articleMulti); + wxMpMaterialArticleUpdateMulti.setIndex(1); + boolean resultMulti = wxService.materialNewsUpdate(wxMpMaterialArticleUpdateMulti); + Assert.assertTrue(resultMulti); + wxMpMaterialNewsMultiple = wxService.materialNewsInfo(multiNewsMediaId); + Assert.assertNotNull(wxMpMaterialNewsMultiple); + Assert.assertEquals("content 2 update", wxMpMaterialNewsMultiple.getArticles().get(1).getContent()); + } + + + @Test(dependsOnMethods = {"testUpdateNewsInfo"}) + public void testMaterialNewsList() throws WxErrorException { + WxMpMaterialNewsBatchGetResult wxMpMaterialNewsBatchGetResult = wxService.materialNewsBatchGet(WxConsts.MATERIAL_NEWS, 0, 20); + return; + } + + @Test(dependsOnMethods = {"testMaterialNewsList"}) + public void testMaterialFileList() throws WxErrorException { + WxMpMaterialFileBatchGetResult wxMpMaterialVoiceBatchGetResult = wxService.materialFileBatchGet(WxConsts.MATERIAL_VOICE, 0, 20); + WxMpMaterialFileBatchGetResult wxMpMaterialVideoBatchGetResult = wxService.materialFileBatchGet(WxConsts.MATERIAL_VIDEO, 0, 20); + WxMpMaterialFileBatchGetResult wxMpMaterialImageBatchGetResult = wxService.materialFileBatchGet(WxConsts.MATERIAL_IMAGE, 0, 20); + return; + } + + @Test(dependsOnMethods = {"testMaterialFileList"}, dataProvider = "allTestMaterial") + public void testDeleteMaterial(String mediaId) throws WxErrorException { + boolean result = wxService.materialDelete(mediaId); + Assert.assertTrue(result); + } + + @DataProvider + public Object[][] downloadMaterial() { + Object[][] params = new Object[this.media_ids.size()][]; + int index = 0; + for (Iterator iterator = this.media_ids.keySet().iterator(); iterator.hasNext(); ) { + params[index] = new Object[]{iterator.next()}; + index++; + } + return params; + } + + @DataProvider + public Iterator allTestMaterial() { + List params = new ArrayList(); + for (Iterator iterator = this.media_ids.keySet().iterator(); iterator.hasNext(); ) { + params.add(new Object[]{iterator.next()}); + } + params.add(new Object[]{this.singleNewsMediaId}); + params.add(new Object[]{this.multiNewsMediaId}); + return params.iterator(); + } +}