From 9302b2e68c60975999f9198b2f673b2c27df1612 Mon Sep 17 00:00:00 2001 From: Allen Date: Tue, 16 Apr 2019 16:46:03 +0800 Subject: [PATCH 1/4] =?UTF-8?q?[update]=20WebWeixinApi=E6=94=B9=E4=B8=BAWe?= =?UTF-8?q?bWeixinApiUtil=E5=B7=A5=E5=85=B7=E7=B1=BB=E6=96=B9=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 - src/main/java/com/hotlcc/wechat4j/Wechat.java | 39 +++-- .../WebWeixinApiUtil.java} | 134 +++++++++--------- src/test/java/TestClass.java | 3 - 4 files changed, 83 insertions(+), 95 deletions(-) rename src/main/java/com/hotlcc/wechat4j/{api/WebWeixinApi.java => util/WebWeixinApiUtil.java} (88%) diff --git a/README.md b/README.md index 02b27de..1aeddd8 100644 --- a/README.md +++ b/README.md @@ -17,10 +17,8 @@ ## 简单使用 ```java -WebWeixinApi api = new WebWeixinApi(); // 实例化微信客户端 Wechat wechat = new Wechat(); -wechat.setWebWeixinApi(api); // 自动登录 wechat.autoLogin(); ``` diff --git a/src/main/java/com/hotlcc/wechat4j/Wechat.java b/src/main/java/com/hotlcc/wechat4j/Wechat.java index bd7e0eb..84f8df4 100644 --- a/src/main/java/com/hotlcc/wechat4j/Wechat.java +++ b/src/main/java/com/hotlcc/wechat4j/Wechat.java @@ -2,7 +2,6 @@ package com.hotlcc.wechat4j; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; -import com.hotlcc.wechat4j.api.WebWeixinApi; import com.hotlcc.wechat4j.enums.*; import com.hotlcc.wechat4j.handler.ExitEventHandler; import com.hotlcc.wechat4j.handler.ReceivedMsgHandler; @@ -39,8 +38,6 @@ import java.util.concurrent.locks.ReentrantLock; public class Wechat { private static Logger logger = LoggerFactory.getLogger(Wechat.class); - private WebWeixinApi webWeixinApi; - private CookieStore cookieStore; private HttpClient httpClient; @@ -78,10 +75,6 @@ public class Wechat { this(new BasicCookieStore()); } - public void setWebWeixinApi(WebWeixinApi webWeixinApi) { - this.webWeixinApi = webWeixinApi; - } - /** * 获取Cookie * @@ -216,7 +209,7 @@ public class Wechat { pw.print("\t第" + i + "次尝试..."); pw.flush(); } - JSONObject result = webWeixinApi.getWxUuid(httpClient); + JSONObject result = WebWeixinApiUtil.getWxUuid(httpClient); if (result == null) { pw.println("\t失败:出现异常"); @@ -265,7 +258,7 @@ public class Wechat { pw.flush(); } - byte[] data = webWeixinApi.getQR(httpClient, uuid); + byte[] data = WebWeixinApiUtil.getQR(httpClient, uuid); if (data == null || data.length <= 0) { pw.print("\t失败"); @@ -302,7 +295,7 @@ public class Wechat { boolean flag = false; while (true) { - JSONObject result = webWeixinApi.getRedirectUri(httpClient, LoginTipEnum.TIP_0, uuid); + JSONObject result = WebWeixinApiUtil.getRedirectUri(httpClient, LoginTipEnum.TIP_0, uuid); if (result == null) { pw.println("\t失败:出现异常"); pw.flush(); @@ -343,7 +336,7 @@ public class Wechat { pw.print("获取登录认证码..."); pw.flush(); - JSONObject result = webWeixinApi.getLoginCode(httpClient, redirectUri); + JSONObject result = WebWeixinApiUtil.getLoginCode(httpClient, redirectUri); if (result == null) { pw.println("\t失败:出现异常"); pw.flush(); @@ -379,7 +372,7 @@ public class Wechat { pw.print("尝试push方式获取uuid..."); pw.flush(); - JSONObject result = webWeixinApi.pushLogin(httpClient, urlVersion, wxuin); + JSONObject result = WebWeixinApiUtil.pushLogin(httpClient, urlVersion, wxuin); if (result == null) { pw.println("\t失败:出现异常"); pw.flush(); @@ -412,7 +405,7 @@ public class Wechat { * @return */ private boolean wxInit() { - JSONObject result = webWeixinApi.webWeixinInit(httpClient, urlVersion, passTicket, new BaseRequest(wxsid, skey, wxuin)); + JSONObject result = WebWeixinApiUtil.webWeixinInit(httpClient, urlVersion, passTicket, new BaseRequest(wxsid, skey, wxuin)); if (result == null) { return false; } @@ -476,7 +469,7 @@ public class Wechat { */ private boolean statusNotify(int time) { for (int i = 0; i < time; i++) { - JSONObject result = webWeixinApi.statusNotify(httpClient, urlVersion, passTicket, new BaseRequest(wxsid, skey, wxuin), getLoginUserName(false)); + JSONObject result = WebWeixinApiUtil.statusNotify(httpClient, urlVersion, passTicket, new BaseRequest(wxsid, skey, wxuin), getLoginUserName(false)); if (result == null) { continue; } @@ -593,7 +586,7 @@ public class Wechat { isOnlineLock.lock(); if (isOnline) { - webWeixinApi.logout(httpClient, urlVersion, new BaseRequest(wxsid, skey, wxuin)); + WebWeixinApiUtil.logout(httpClient, urlVersion, new BaseRequest(wxsid, skey, wxuin)); isOnline = false; if (clearAllLoginInfo) { @@ -663,7 +656,7 @@ public class Wechat { long start = System.currentTimeMillis(); try { - JSONObject result = webWeixinApi.syncCheck(httpClient, urlVersion, new BaseRequest(wxsid, skey, wxuin), getSyncKeyList(false)); + JSONObject result = WebWeixinApiUtil.syncCheck(httpClient, urlVersion, new BaseRequest(wxsid, skey, wxuin), getSyncKeyList(false)); logger.info("微信同步监听心跳返回数据:{}", result); if (result == null) { throw new RuntimeException("微信API调用异常"); @@ -797,7 +790,7 @@ public class Wechat { */ private void webWxSync() { try { - JSONObject result = webWeixinApi.webWxSync(httpClient, urlVersion, passTicket, new BaseRequest(wxsid, skey, wxuin), syncKey); + JSONObject result = WebWeixinApiUtil.webWxSync(httpClient, urlVersion, passTicket, new BaseRequest(wxsid, skey, wxuin), syncKey); if (result == null) { logger.error("从服务端同步新数据异常"); return; @@ -879,7 +872,7 @@ public class Wechat { */ public UserInfo getLoginUser(boolean update) { if (loginUser == null || update) { - JSONObject result = webWeixinApi.webWeixinInit(httpClient, urlVersion, passTicket, new BaseRequest(wxsid, skey, wxuin)); + JSONObject result = WebWeixinApiUtil.webWeixinInit(httpClient, urlVersion, passTicket, new BaseRequest(wxsid, skey, wxuin)); if (result == null) { return loginUser; } @@ -954,7 +947,7 @@ public class Wechat { */ private JSONObject getSyncKey(boolean update) { if (syncKey == null || update) { - JSONObject result = webWeixinApi.webWeixinInit(httpClient, urlVersion, passTicket, new BaseRequest(wxsid, skey, wxuin)); + JSONObject result = WebWeixinApiUtil.webWeixinInit(httpClient, urlVersion, passTicket, new BaseRequest(wxsid, skey, wxuin)); if (result == null) { return syncKey; } @@ -1005,7 +998,7 @@ public class Wechat { */ public List getContactList(boolean update) { if (contactList == null || update) { - JSONObject result = webWeixinApi.getContact(httpClient, urlVersion, passTicket, skey); + JSONObject result = WebWeixinApiUtil.getContact(httpClient, urlVersion, passTicket, skey); if (result == null) { return contactList; } @@ -1164,7 +1157,7 @@ public class Wechat { } message.setType(MsgTypeEnum.TEXT_MSG.getCode()); - return webWeixinApi.sendMsg(httpClient, urlVersion, passTicket, baseRequest, message); + return WebWeixinApiUtil.sendMsg(httpClient, urlVersion, passTicket, baseRequest, message); } /** @@ -1266,7 +1259,7 @@ public class Wechat { // 上传媒体文件 String dataTicket = getCookieValue("webwx_data_ticket"); - JSONObject result = webWeixinApi.uploadMedia(httpClient, urlVersion, passTicket, baseRequest, loginUserName, toUserName, dataTicket, mediaData, mediaName, contentType); + JSONObject result = WebWeixinApiUtil.uploadMedia(httpClient, urlVersion, passTicket, baseRequest, loginUserName, toUserName, dataTicket, mediaData, mediaName, contentType); if (result == null) { return null; } @@ -1294,7 +1287,7 @@ public class Wechat { message.setMediaId(mediaId); message.setToUserName(toUserName); message.setType(MsgTypeEnum.IMAGE_MSG.getCode()); - result = webWeixinApi.sendImageMsg(httpClient, urlVersion, passTicket, baseRequest, message); + result = WebWeixinApiUtil.sendImageMsg(httpClient, urlVersion, passTicket, baseRequest, message); return result; } diff --git a/src/main/java/com/hotlcc/wechat4j/api/WebWeixinApi.java b/src/main/java/com/hotlcc/wechat4j/util/WebWeixinApiUtil.java similarity index 88% rename from src/main/java/com/hotlcc/wechat4j/api/WebWeixinApi.java rename to src/main/java/com/hotlcc/wechat4j/util/WebWeixinApiUtil.java index b55cb39..b3dc0ad 100644 --- a/src/main/java/com/hotlcc/wechat4j/api/WebWeixinApi.java +++ b/src/main/java/com/hotlcc/wechat4j/util/WebWeixinApiUtil.java @@ -1,4 +1,4 @@ -package com.hotlcc.wechat4j.api; +package com.hotlcc.wechat4j.util; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; @@ -6,9 +6,6 @@ import com.hotlcc.wechat4j.enums.LoginTipEnum; import com.hotlcc.wechat4j.model.BaseRequest; import com.hotlcc.wechat4j.model.MediaMessage; import com.hotlcc.wechat4j.model.WxMessage; -import com.hotlcc.wechat4j.util.PropertiesUtil; -import com.hotlcc.wechat4j.util.StringUtil; -import com.hotlcc.wechat4j.util.WechatUtil; import org.apache.commons.codec.digest.DigestUtils; import org.apache.http.*; import org.apache.http.client.HttpClient; @@ -40,8 +37,11 @@ import java.util.regex.Pattern; * @author Allen */ @SuppressWarnings({"Duplicates", "unused"}) -public class WebWeixinApi { - private static Logger logger = LoggerFactory.getLogger(WebWeixinApi.class); +public final class WebWeixinApiUtil { + private WebWeixinApiUtil() { + } + + private static Logger logger = LoggerFactory.getLogger(WebWeixinApiUtil.class); /** * 预编译正则匹配 @@ -63,7 +63,7 @@ public class WebWeixinApi { * @param httpClient http客户端 * @return 返回数据 */ - public JSONObject getWxUuid(HttpClient httpClient) { + public static JSONObject getWxUuid(HttpClient httpClient) { try { String url = new ST(PropertiesUtil.getProperty("webwx-url.uuid_url")) .add("appid", PropertiesUtil.getProperty("webwx.appid")) @@ -120,8 +120,8 @@ public class WebWeixinApi { * @param uuid uuid * @return 二维码图片字节数据 */ - public byte[] getQR(HttpClient httpClient, - String uuid) { + public static byte[] getQR(HttpClient httpClient, + String uuid) { try { String url = new ST(PropertiesUtil.getProperty("webwx-url.qrcode_url")) .add("uuid", uuid) @@ -157,9 +157,9 @@ public class WebWeixinApi { * @param uuid uuid * @return 返回数据 */ - public JSONObject getRedirectUri(HttpClient httpClient, - LoginTipEnum tip, - String uuid) { + public static JSONObject getRedirectUri(HttpClient httpClient, + LoginTipEnum tip, + String uuid) { try { long millis = System.currentTimeMillis(); String url = new ST(PropertiesUtil.getProperty("webwx-url.redirect_uri")) @@ -229,8 +229,8 @@ public class WebWeixinApi { * @param redirectUri 调整uri * @return 返回数据 */ - public JSONObject getLoginCode(HttpClient httpClient, - String redirectUri) { + public static JSONObject getLoginCode(HttpClient httpClient, + String redirectUri) { try { String url = new ST(PropertiesUtil.getProperty("webwx-url.newlogin_url")) .add("redirectUri", redirectUri) @@ -262,9 +262,9 @@ public class WebWeixinApi { * @param urlVersion url版本号 * @param baseRequest BaseRequest */ - public void logout(HttpClient httpClient, - String urlVersion, - BaseRequest baseRequest) { + public static void logout(HttpClient httpClient, + String urlVersion, + BaseRequest baseRequest) { try { List pairList = new ArrayList<>(); pairList.add(new BasicNameValuePair("sid", baseRequest.getSid())); @@ -299,9 +299,9 @@ public class WebWeixinApi { * @param wxuin uin * @return 返回数据 */ - public JSONObject pushLogin(HttpClient httpClient, - String urlVersion, - String wxuin) { + public static JSONObject pushLogin(HttpClient httpClient, + String urlVersion, + String wxuin) { try { String url = new ST(PropertiesUtil.getProperty("webwx-url.pushlogin_url")) .add("urlVersion", urlVersion) @@ -336,10 +336,10 @@ public class WebWeixinApi { * @param baseRequest BaseRequest * @return 返回数据 */ - public JSONObject webWeixinInit(HttpClient httpClient, - String urlVersion, - String passticket, - BaseRequest baseRequest) { + public static JSONObject webWeixinInit(HttpClient httpClient, + String urlVersion, + String passticket, + BaseRequest baseRequest) { try { String url = new ST(PropertiesUtil.getProperty("webwx-url.webwxinit_url")) .add("urlVersion", urlVersion) @@ -381,11 +381,11 @@ public class WebWeixinApi { * @param loginUserName 当前登录账号用户名 * @return 返回数据 */ - public JSONObject statusNotify(HttpClient httpClient, - String urlVersion, - String passticket, - BaseRequest baseRequest, - String loginUserName) { + public static JSONObject statusNotify(HttpClient httpClient, + String urlVersion, + String passticket, + BaseRequest baseRequest, + String loginUserName) { try { String url = new ST(PropertiesUtil.getProperty("webwx-url.statusnotify_url")) .add("urlVersion", urlVersion) @@ -429,10 +429,10 @@ public class WebWeixinApi { * @param syncKeyList SyncKeyList * @return 返回数据 */ - public JSONObject syncCheck(HttpClient httpClient, - String urlVersion, - BaseRequest baseRequest, - JSONArray syncKeyList) { + public static JSONObject syncCheck(HttpClient httpClient, + String urlVersion, + BaseRequest baseRequest, + JSONArray syncKeyList) { try { long millis = System.currentTimeMillis(); String url = new ST(PropertiesUtil.getProperty("webwx-url.synccheck_url")) @@ -488,10 +488,10 @@ public class WebWeixinApi { * @param skey skey * @return 返回数据 */ - public JSONObject getContact(HttpClient httpClient, - String urlVersion, - String passticket, - String skey) { + public static JSONObject getContact(HttpClient httpClient, + String urlVersion, + String passticket, + String skey) { try { String url = new ST(PropertiesUtil.getProperty("webwx-url.getcontact_url")) .add("urlVersion", urlVersion) @@ -528,11 +528,11 @@ public class WebWeixinApi { * @param batchContactList 联系人列表 * @return 返回数据 */ - public JSONObject batchGetContact(HttpClient httpClient, - String urlVersion, - String passticket, - BaseRequest baseRequest, - JSONArray batchContactList) { + public static JSONObject batchGetContact(HttpClient httpClient, + String urlVersion, + String passticket, + BaseRequest baseRequest, + JSONArray batchContactList) { try { String url = new ST(PropertiesUtil.getProperty("webwx-url.batchgetcontact_url")) .add("urlVersion", urlVersion) @@ -576,11 +576,11 @@ public class WebWeixinApi { * @param syncKey syncKey * @return 返回数据 */ - public JSONObject webWxSync(HttpClient httpClient, - String urlVersion, - String passticket, - BaseRequest baseRequest, - JSONObject syncKey) { + public static JSONObject webWxSync(HttpClient httpClient, + String urlVersion, + String passticket, + BaseRequest baseRequest, + JSONObject syncKey) { try { String url = new ST(PropertiesUtil.getProperty("webwx-url.webwxsync_url")) .add("urlVersion", urlVersion) @@ -624,11 +624,11 @@ public class WebWeixinApi { * @param message 消息 * @return 返回数据 */ - public JSONObject sendMsg(HttpClient httpClient, - String urlVersion, - String passticket, - BaseRequest baseRequest, - WxMessage message) { + public static JSONObject sendMsg(HttpClient httpClient, + String urlVersion, + String passticket, + BaseRequest baseRequest, + WxMessage message) { try { String url = new ST(PropertiesUtil.getProperty("webwx-url.webwxsendmsg_url")) .add("urlVersion", urlVersion) @@ -676,16 +676,16 @@ public class WebWeixinApi { * @param contentType 媒体文件类型 * @return 返回数据 */ - public JSONObject uploadMedia(HttpClient httpClient, - String urlVersion, - String passticket, - BaseRequest baseRequest, - String fromUserName, - String toUserName, - String dataTicket, - byte[] mediaData, - String mediaName, - ContentType contentType) { + public static JSONObject uploadMedia(HttpClient httpClient, + String urlVersion, + String passticket, + BaseRequest baseRequest, + String fromUserName, + String toUserName, + String dataTicket, + byte[] mediaData, + String mediaName, + ContentType contentType) { try { String url = new ST(PropertiesUtil.getProperty("webwx-url.uploadmedia_url")) .add("urlVersion", urlVersion) @@ -778,11 +778,11 @@ public class WebWeixinApi { * @param message 消息 * @return 返回数据 */ - public JSONObject sendImageMsg(HttpClient httpClient, - String urlVersion, - String passticket, - BaseRequest baseRequest, - MediaMessage message) { + public static JSONObject sendImageMsg(HttpClient httpClient, + String urlVersion, + String passticket, + BaseRequest baseRequest, + MediaMessage message) { try { String url = new ST(PropertiesUtil.getProperty("webwx-url.webwxsendmsgimg_url")) .add("urlVersion", urlVersion) diff --git a/src/test/java/TestClass.java b/src/test/java/TestClass.java index 92bb6a8..fdd99da 100644 --- a/src/test/java/TestClass.java +++ b/src/test/java/TestClass.java @@ -1,6 +1,5 @@ import com.alibaba.fastjson.JSONObject; import com.hotlcc.wechat4j.Wechat; -import com.hotlcc.wechat4j.api.WebWeixinApi; import com.hotlcc.wechat4j.handler.ReceivedMsgHandler; import com.hotlcc.wechat4j.model.ReceivedMsg; import com.hotlcc.wechat4j.model.UserInfo; @@ -16,8 +15,6 @@ public class TestClass { @Before public void initAndLogin() { wechat = new Wechat(); - WebWeixinApi api = new WebWeixinApi(); - wechat.setWebWeixinApi(api); wechat.addReceivedMsgHandler(new ReceivedMsgHandler() { @Override public void handleAllType(Wechat wechat, ReceivedMsg msg) { From 11f3b995242e3c58c368733381e9642cd070c5b8 Mon Sep 17 00:00:00 2001 From: Allen Date: Tue, 16 Apr 2019 16:51:55 +0800 Subject: [PATCH 2/4] =?UTF-8?q?[update]=20=E6=97=A5=E5=BF=97=E6=A1=86?= =?UTF-8?q?=E6=9E=B6=E4=BD=BF=E7=94=A8=E6=96=B9=E5=BC=8F=E5=8F=98=E6=9B=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/hotlcc/wechat4j/Wechat.java | 44 +++++++++---------- .../com/hotlcc/wechat4j/util/CommonUtil.java | 6 +-- .../com/hotlcc/wechat4j/util/FileUtil.java | 6 +-- .../hotlcc/wechat4j/util/PropertiesUtil.java | 8 ++-- .../com/hotlcc/wechat4j/util/QRCodeUtil.java | 8 ++-- .../wechat4j/util/WebWeixinApiUtil.java | 43 +++++++----------- 6 files changed, 48 insertions(+), 67 deletions(-) diff --git a/src/main/java/com/hotlcc/wechat4j/Wechat.java b/src/main/java/com/hotlcc/wechat4j/Wechat.java index 84f8df4..d167f55 100644 --- a/src/main/java/com/hotlcc/wechat4j/Wechat.java +++ b/src/main/java/com/hotlcc/wechat4j/Wechat.java @@ -7,6 +7,7 @@ import com.hotlcc.wechat4j.handler.ExitEventHandler; import com.hotlcc.wechat4j.handler.ReceivedMsgHandler; import com.hotlcc.wechat4j.model.*; import com.hotlcc.wechat4j.util.*; +import lombok.extern.slf4j.Slf4j; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; @@ -17,8 +18,6 @@ import org.apache.http.entity.ContentType; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.HttpClients; import org.apache.http.protocol.HttpContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; @@ -35,9 +34,8 @@ import java.util.concurrent.locks.ReentrantLock; * @author Allen */ @SuppressWarnings({"Duplicates", "unused"}) +@Slf4j public class Wechat { - private static Logger logger = LoggerFactory.getLogger(Wechat.class); - private CookieStore cookieStore; private HttpClient httpClient; @@ -657,7 +655,7 @@ public class Wechat { try { JSONObject result = WebWeixinApiUtil.syncCheck(httpClient, urlVersion, new BaseRequest(wxsid, skey, wxuin), getSyncKeyList(false)); - logger.info("微信同步监听心跳返回数据:{}", result); + log.info("微信同步监听心跳返回数据:{}", result); if (result == null) { throw new RuntimeException("微信API调用异常"); } else { @@ -667,7 +665,7 @@ public class Wechat { //人为退出 int retcode = result.getIntValue("retcode"); if (retcode != RetcodeEnum.RECODE_0.getCode()) { - logger.info("微信退出或从其它设备登录"); + log.info("微信退出或从其它设备登录"); logout(); processExitEvent(ExitTypeEnum.REMOTE_EXIT, null); return; @@ -676,16 +674,16 @@ public class Wechat { int selector = result.getIntValue("selector"); processSelector(selector); } catch (Exception e) { - logger.error("同步监听心跳异常", e); + log.error("同步监听心跳异常", e); if (i == 0) { - logger.info("同步监听请求失败,正在重试..."); + log.info("同步监听请求失败,正在重试..."); } else if (i > 0) { - logger.info("第{}次重试失败" + i); + log.info("第{}次重试失败" + i); } if (i >= time) { - logger.info("重复{}次仍然失败,退出微信", i); + log.info("重复{}次仍然失败,退出微信", i); logout(); processExitEvent(ExitTypeEnum.ERROR_EXIT, e); return; @@ -722,7 +720,7 @@ public class Wechat { } } } catch (Exception e) { - logger.error("Exit event process error.", e); + log.error("Exit event process error.", e); } } @@ -742,13 +740,13 @@ public class Wechat { break; } } catch (Exception e) { - logger.error("Exit event process error.", e); + log.error("Exit event process error.", e); } try { handler.handleAllType(wechat, type, t); } catch (Exception e) { - logger.error("Exit event process error.", e); + log.error("Exit event process error.", e); } } @@ -761,7 +759,7 @@ public class Wechat { try { SelectorEnum e = SelectorEnum.valueOf(selector); if (e == null) { - logger.warn("Cannot process unknow selector {}", selector); + log.warn("Cannot process unknow selector {}", selector); return; } @@ -781,7 +779,7 @@ public class Wechat { break; } } catch (Exception e) { - logger.error("Execute processSelector error.", e); + log.error("Execute processSelector error.", e); } } @@ -792,19 +790,19 @@ public class Wechat { try { JSONObject result = WebWeixinApiUtil.webWxSync(httpClient, urlVersion, passTicket, new BaseRequest(wxsid, skey, wxuin), syncKey); if (result == null) { - logger.error("从服务端同步新数据异常"); + log.error("从服务端同步新数据异常"); return; } JSONObject baseResponse = result.getJSONObject("BaseResponse"); if (baseResponse == null) { - logger.warn("同步接口返回数据格式错误"); + log.warn("同步接口返回数据格式错误"); return; } int ret = baseResponse.getIntValue("Ret"); if (ret != RetcodeEnum.RECODE_0.getCode()) { - logger.warn("同步接口返回错误代码:{}", ret); + log.warn("同步接口返回错误代码:{}", ret); return; } @@ -820,7 +818,7 @@ public class Wechat { syncKeyLock.unlock(); } } catch (Exception e) { - logger.error("Execute webWxSync error.", e); + log.error("Execute webWxSync error.", e); } } @@ -836,10 +834,10 @@ public class Wechat { } int len = addMsgList.size(); - logger.debug("收到{}条新消息", len); + log.debug("收到{}条新消息", len); if (receivedMsgHandlers == null || receivedMsgHandlers.isEmpty()) { - logger.warn("收到{}条新消息,但没有配置消息处理器", len); + log.warn("收到{}条新消息,但没有配置消息处理器", len); return; } @@ -852,7 +850,7 @@ public class Wechat { } } } catch (Exception e) { - logger.error("Execute processNewMsg error.", e); + log.error("Execute processNewMsg error.", e); } } @@ -860,7 +858,7 @@ public class Wechat { try { handler.handleAllType(wechat, msg); } catch (Exception e) { - logger.error("Execute processNewMsg error.", e); + log.error("Execute processNewMsg error.", e); } } } diff --git a/src/main/java/com/hotlcc/wechat4j/util/CommonUtil.java b/src/main/java/com/hotlcc/wechat4j/util/CommonUtil.java index 734f015..d58c961 100644 --- a/src/main/java/com/hotlcc/wechat4j/util/CommonUtil.java +++ b/src/main/java/com/hotlcc/wechat4j/util/CommonUtil.java @@ -1,16 +1,14 @@ package com.hotlcc.wechat4j.util; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; /** * 通用工具类 * * @author Allen */ +@Slf4j public final class CommonUtil { - private static Logger logger = LoggerFactory.getLogger(CommonUtil.class); - private CommonUtil() { } diff --git a/src/main/java/com/hotlcc/wechat4j/util/FileUtil.java b/src/main/java/com/hotlcc/wechat4j/util/FileUtil.java index f323e23..eb1c194 100644 --- a/src/main/java/com/hotlcc/wechat4j/util/FileUtil.java +++ b/src/main/java/com/hotlcc/wechat4j/util/FileUtil.java @@ -1,8 +1,7 @@ package com.hotlcc.wechat4j.util; +import lombok.extern.slf4j.Slf4j; import org.apache.http.entity.ContentType; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import javax.activation.MimetypesFileTypeMap; import java.io.ByteArrayOutputStream; @@ -15,9 +14,8 @@ import java.io.IOException; * * @author Allen */ +@Slf4j public final class FileUtil { - private static Logger logger = LoggerFactory.getLogger(FileUtil.class); - private FileUtil() { } diff --git a/src/main/java/com/hotlcc/wechat4j/util/PropertiesUtil.java b/src/main/java/com/hotlcc/wechat4j/util/PropertiesUtil.java index 104b723..f36d28b 100644 --- a/src/main/java/com/hotlcc/wechat4j/util/PropertiesUtil.java +++ b/src/main/java/com/hotlcc/wechat4j/util/PropertiesUtil.java @@ -1,7 +1,6 @@ package com.hotlcc.wechat4j.util; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; import java.io.IOException; import java.io.InputStream; @@ -12,9 +11,8 @@ import java.util.Properties; * * @author Allen */ +@Slf4j public final class PropertiesUtil { - private static Logger logger = LoggerFactory.getLogger(PropertiesUtil.class); - private PropertiesUtil() { } @@ -38,7 +36,7 @@ public final class PropertiesUtil { is = PropertiesUtil.class.getClassLoader().getResourceAsStream(path); prop.load(is); } catch (Exception e) { - logger.error("Loading properties file \"" + path + "\" error.", e); + log.error("Loading properties file \"" + path + "\" error.", e); } finally { if (is != null) { try { diff --git a/src/main/java/com/hotlcc/wechat4j/util/QRCodeUtil.java b/src/main/java/com/hotlcc/wechat4j/util/QRCodeUtil.java index 26cc1b6..df64c8c 100644 --- a/src/main/java/com/hotlcc/wechat4j/util/QRCodeUtil.java +++ b/src/main/java/com/hotlcc/wechat4j/util/QRCodeUtil.java @@ -7,8 +7,7 @@ import com.google.zxing.client.j2se.BufferedImageLuminanceSource; import com.google.zxing.common.BitMatrix; import com.google.zxing.common.HybridBinarizer; import com.hotlcc.wechat4j.enums.OperatingSystemEnum; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import lombok.extern.slf4j.Slf4j; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; @@ -23,9 +22,8 @@ import java.io.IOException; * @author Allen */ @SuppressWarnings({"unused", "WeakerAccess"}) +@Slf4j public final class QRCodeUtil { - private static Logger logger = LoggerFactory.getLogger(QRCodeUtil.class); - private QRCodeUtil() { } @@ -252,7 +250,7 @@ public final class QRCodeUtil { fos.flush(); return tmp; } catch (IOException e) { - logger.error("二维码写入临时文件异常", e); + log.error("二维码写入临时文件异常", e); throw new RuntimeException(e); } finally { if (fos != null) { diff --git a/src/main/java/com/hotlcc/wechat4j/util/WebWeixinApiUtil.java b/src/main/java/com/hotlcc/wechat4j/util/WebWeixinApiUtil.java index b3dc0ad..1ec8ae6 100644 --- a/src/main/java/com/hotlcc/wechat4j/util/WebWeixinApiUtil.java +++ b/src/main/java/com/hotlcc/wechat4j/util/WebWeixinApiUtil.java @@ -6,6 +6,7 @@ import com.hotlcc.wechat4j.enums.LoginTipEnum; import com.hotlcc.wechat4j.model.BaseRequest; import com.hotlcc.wechat4j.model.MediaMessage; import com.hotlcc.wechat4j.model.WxMessage; +import lombok.extern.slf4j.Slf4j; import org.apache.commons.codec.digest.DigestUtils; import org.apache.http.*; import org.apache.http.client.HttpClient; @@ -20,8 +21,6 @@ import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.json.XML; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.stringtemplate.v4.ST; import java.math.BigDecimal; @@ -37,12 +36,11 @@ import java.util.regex.Pattern; * @author Allen */ @SuppressWarnings({"Duplicates", "unused"}) +@Slf4j public final class WebWeixinApiUtil { private WebWeixinApiUtil() { } - private static Logger logger = LoggerFactory.getLogger(WebWeixinApiUtil.class); - /** * 预编译正则匹配 */ @@ -108,7 +106,7 @@ public final class WebWeixinApiUtil { return result; } catch (Exception e) { - logger.error("获取uuid异常", e); + log.error("获取uuid异常", e); return null; } } @@ -144,7 +142,7 @@ public final class WebWeixinApiUtil { return data; } catch (Exception e) { - logger.error("获取二维码异常", e); + log.error("获取二维码异常", e); return null; } } @@ -216,7 +214,7 @@ public final class WebWeixinApiUtil { return result; } catch (Exception e) { - logger.error("获取跳转uri异常", e); + log.error("获取跳转uri异常", e); return null; } } @@ -250,7 +248,7 @@ public final class WebWeixinApiUtil { return JSONObject.parseObject(XML.toJSONObject(res).toString()).getJSONObject("error"); } catch (Exception e) { - logger.error("获取登录认证码异常", e); + log.error("获取登录认证码异常", e); return null; } } @@ -287,7 +285,7 @@ public final class WebWeixinApiUtil { httpClient.execute(httpPost); } } catch (Exception e) { - logger.error("退出登录异常", e); + log.error("退出登录异常", e); } } @@ -322,7 +320,7 @@ public final class WebWeixinApiUtil { return JSONObject.parseObject(res); } catch (Exception e) { - logger.error("push登录异常", e); + log.error("push登录异常", e); return null; } } @@ -366,7 +364,7 @@ public final class WebWeixinApiUtil { return JSONObject.parseObject(res); } catch (Exception e) { - logger.error("获取初始化数据异常", e); + log.error("获取初始化数据异常", e); return null; } } @@ -415,7 +413,7 @@ public final class WebWeixinApiUtil { return JSONObject.parseObject(res); } catch (Exception e) { - logger.error("开启消息状态通知异常", e); + log.error("开启消息状态通知异常", e); return null; } } @@ -474,7 +472,7 @@ public final class WebWeixinApiUtil { return result; } catch (Exception e) { - logger.error("服务端状态同步异常", e); + log.error("服务端状态同步异常", e); return null; } } @@ -513,7 +511,7 @@ public final class WebWeixinApiUtil { return JSONObject.parseObject(res); } catch (Exception e) { - logger.error("获取全部联系人列表异常", e); + log.error("获取全部联系人列表异常", e); return null; } } @@ -561,7 +559,7 @@ public final class WebWeixinApiUtil { return JSONObject.parseObject(res); } catch (Exception e) { - logger.error("批量获取指定联系人信息异常", e); + log.error("批量获取指定联系人信息异常", e); return null; } } @@ -609,7 +607,7 @@ public final class WebWeixinApiUtil { return JSONObject.parseObject(res); } catch (Exception e) { - logger.error("从服务端同步新数据异常", e); + log.error("从服务端同步新数据异常", e); return null; } } @@ -656,7 +654,7 @@ public final class WebWeixinApiUtil { return JSONObject.parseObject(res); } catch (Exception e) { - logger.error("发送消息异常", e); + log.error("发送消息异常", e); return null; } } @@ -693,7 +691,6 @@ public final class WebWeixinApiUtil { long millis = System.currentTimeMillis(); int mediaLength = mediaData.length; - // String mimeType = contentType.getMimeType(); HttpPost httpPost = new HttpPost(url); httpPost.setHeader("Content-type", ContentType.MULTIPART_FORM_DATA.toString()); @@ -722,14 +719,8 @@ public final class WebWeixinApiUtil { HttpEntity paramEntity = MultipartEntityBuilder.create() .setMode(HttpMultipartMode.BROWSER_COMPATIBLE) - // .addTextBody("id", StringUtil.getUuid(), ContentType.TEXT_PLAIN) - // .addTextBody("name", mediaName, ContentType.TEXT_PLAIN) - // .addTextBody("type", mimeType, ContentType.TEXT_PLAIN) - // .addTextBody("lastModifieDate", String.valueOf(millis), ContentType.TEXT_PLAIN) - // .addTextBody("size", String.valueOf(mediaLength), ContentType.TEXT_PLAIN) .addTextBody("chunks", String.valueOf(chunks)) .addTextBody("chunk", String.valueOf(chunk)) - // .addTextBody("mediatype", WechatUtil.getMediatype(mimeType), ContentType.TEXT_PLAIN) .addTextBody("uploadmediarequest", uploadmediarequest.toJSONString(), ContentType.TEXT_PLAIN) .addTextBody("webwx_data_ticket", dataTicket, ContentType.TEXT_PLAIN) .addTextBody("pass_ticket", passticket, ContentType.TEXT_PLAIN) @@ -763,7 +754,7 @@ public final class WebWeixinApiUtil { return result; } catch (Exception e) { - logger.error("上传媒体文件异常", e); + log.error("上传媒体文件异常", e); return null; } } @@ -810,7 +801,7 @@ public final class WebWeixinApiUtil { return JSONObject.parseObject(res); } catch (Exception e) { - logger.error("发送图片消息异常", e); + log.error("发送图片消息异常", e); return null; } } From a8a2b453ec3082ffe000549537ce3c540d66b995 Mon Sep 17 00:00:00 2001 From: Allen Date: Wed, 17 Apr 2019 10:18:22 +0800 Subject: [PATCH 3/4] =?UTF-8?q?[update]=20=E6=96=B0=E5=A2=9E=E8=A7=86?= =?UTF-8?q?=E9=A2=91=E6=B6=88=E6=81=AF=E5=8F=91=E9=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 17 ++ src/main/java/com/hotlcc/wechat4j/Wechat.java | 226 ++++++++++++++++-- .../{ExitTypeEnum.java => ExitType.java} | 10 +- .../{LoginTipEnum.java => LoginTip.java} | 16 +- .../com/hotlcc/wechat4j/enums/MediaType.java | 22 ++ .../enums/{MsgTypeEnum.java => MsgType.java} | 20 +- .../wechat4j/enums/OperatingSystem.java | 35 +++ .../wechat4j/enums/OperatingSystemEnum.java | 38 --- .../enums/{RetcodeEnum.java => Retcode.java} | 22 +- .../{SelectorEnum.java => Selector.java} | 16 +- .../wechat4j/handler/ExitEventHandler.java | 4 +- .../com/hotlcc/wechat4j/util/QRCodeUtil.java | 4 +- .../wechat4j/util/WebWeixinApiUtil.java | 56 ++++- .../META-INF/wechat4j/webwx-url.properties | 4 +- src/test/java/TestClass.java | 11 +- 15 files changed, 381 insertions(+), 120 deletions(-) rename src/main/java/com/hotlcc/wechat4j/enums/{ExitTypeEnum.java => ExitType.java} (69%) rename src/main/java/com/hotlcc/wechat4j/enums/{LoginTipEnum.java => LoginTip.java} (62%) create mode 100644 src/main/java/com/hotlcc/wechat4j/enums/MediaType.java rename src/main/java/com/hotlcc/wechat4j/enums/{MsgTypeEnum.java => MsgType.java} (78%) create mode 100644 src/main/java/com/hotlcc/wechat4j/enums/OperatingSystem.java delete mode 100644 src/main/java/com/hotlcc/wechat4j/enums/OperatingSystemEnum.java rename src/main/java/com/hotlcc/wechat4j/enums/{RetcodeEnum.java => Retcode.java} (54%) rename src/main/java/com/hotlcc/wechat4j/enums/{SelectorEnum.java => Selector.java} (65%) diff --git a/README.md b/README.md index 1aeddd8..645ff1d 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,23 @@ JSONObject sendImage(String userName, String nickName, String remarkName, byte[] JSONObject sendImage(String userName, String nickName, String remarkName, File image); ``` +### 视频消息 + +```java +// 通过userName发送视频消息 +JSONObject sendVideo(String userName, byte[] mediaData, String mediaName, ContentType contentType); +JSONObject sendVideo(String userName, File image); +// 通过昵称发送视频消息 +JSONObject sendVideoToNickName(String nickName, byte[] mediaData, String mediaName, ContentType contentType); +JSONObject sendVideoToNickName(String nickName, File image); +// 通过备注名发送视频消息 +JSONObject sendVideoToRemarkName(String remarkName, byte[] mediaData, String mediaName, ContentType contentType); +JSONObject sendVideoToRemarkName(String remarkName, File image); +// 发送视频消息(根据多种名称) +JSONObject sendVideo(String userName, String nickName, String remarkName, byte[] mediaData, String mediaName, ContentType contentType); +JSONObject sendVideo(String userName, String nickName, String remarkName, File image); +``` + > 更多消息类型支持尽请期待。 ## 消息处理器 diff --git a/src/main/java/com/hotlcc/wechat4j/Wechat.java b/src/main/java/com/hotlcc/wechat4j/Wechat.java index d167f55..05079d5 100644 --- a/src/main/java/com/hotlcc/wechat4j/Wechat.java +++ b/src/main/java/com/hotlcc/wechat4j/Wechat.java @@ -8,7 +8,6 @@ import com.hotlcc.wechat4j.handler.ReceivedMsgHandler; import com.hotlcc.wechat4j.model.*; import com.hotlcc.wechat4j.util.*; import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.client.CookieStore; @@ -20,7 +19,6 @@ import org.apache.http.impl.client.HttpClients; import org.apache.http.protocol.HttpContext; import java.io.File; -import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; @@ -180,7 +178,7 @@ public class Wechat { private HttpClient buildHttpClient(CookieStore cookieStore) { HttpRequestInterceptor interceptor = new HttpRequestInterceptor() { @Override - public void process(HttpRequest httpRequest, HttpContext httpContext) throws HttpException, IOException { + public void process(HttpRequest httpRequest, HttpContext httpContext) { httpRequest.addHeader("User-Agent", PropertiesUtil.getProperty("wechat4j.userAgent")); } }; @@ -194,8 +192,8 @@ public class Wechat { /** * 获取uuid(登录时) * - * @param pw - * @param time + * @param pw 打印器 + * @param time 时间 * @return */ private String getWxUuid(PrintWriter pw, int time) { @@ -244,7 +242,7 @@ public class Wechat { /** * 获取并显示qrcode(登录时) * - * @return + * @return 是否成功 */ private boolean getAndShowQRCode(PrintWriter pw, String uuid, int time) { pw.print("获取二维码..."); @@ -293,7 +291,7 @@ public class Wechat { boolean flag = false; while (true) { - JSONObject result = WebWeixinApiUtil.getRedirectUri(httpClient, LoginTipEnum.TIP_0, uuid); + JSONObject result = WebWeixinApiUtil.getRedirectUri(httpClient, LoginTip.TIP_0, uuid); if (result == null) { pw.println("\t失败:出现异常"); pw.flush(); @@ -664,10 +662,10 @@ public class Wechat { //人为退出 int retcode = result.getIntValue("retcode"); - if (retcode != RetcodeEnum.RECODE_0.getCode()) { + if (retcode != Retcode.RECODE_0.getCode()) { log.info("微信退出或从其它设备登录"); logout(); - processExitEvent(ExitTypeEnum.REMOTE_EXIT, null); + processExitEvent(ExitType.REMOTE_EXIT, null); return; } @@ -685,7 +683,7 @@ public class Wechat { if (i >= time) { log.info("重复{}次仍然失败,退出微信", i); logout(); - processExitEvent(ExitTypeEnum.ERROR_EXIT, e); + processExitEvent(ExitType.ERROR_EXIT, e); return; } @@ -699,7 +697,7 @@ public class Wechat { } } - processExitEvent(ExitTypeEnum.LOCAL_EXIT, null); + processExitEvent(ExitType.LOCAL_EXIT, null); } /** @@ -708,7 +706,7 @@ public class Wechat { * @param type 退出类型 * @param t 异常 */ - private void processExitEvent(ExitTypeEnum type, Throwable t) { + private void processExitEvent(ExitType type, Throwable t) { try { if (exitEventHandlers == null) { return; @@ -724,7 +722,7 @@ public class Wechat { } } - private void processExitEvent(ExitTypeEnum type, Throwable t, ExitEventHandler handler) { + private void processExitEvent(ExitType type, Throwable t, ExitEventHandler handler) { try { switch (type) { case ERROR_EXIT: @@ -757,7 +755,7 @@ public class Wechat { */ private void processSelector(int selector) { try { - SelectorEnum e = SelectorEnum.valueOf(selector); + Selector e = Selector.valueOf(selector); if (e == null) { log.warn("Cannot process unknow selector {}", selector); return; @@ -801,7 +799,7 @@ public class Wechat { } int ret = baseResponse.getIntValue("Ret"); - if (ret != RetcodeEnum.RECODE_0.getCode()) { + if (ret != Retcode.RECODE_0.getCode()) { log.warn("同步接口返回错误代码:{}", ret); return; } @@ -1153,7 +1151,7 @@ public class Wechat { } else { message.setToUserName(userName); } - message.setType(MsgTypeEnum.TEXT_MSG.getCode()); + message.setType(MsgType.TEXT_MSG.getCode()); return WebWeixinApiUtil.sendMsg(httpClient, urlVersion, passTicket, baseRequest, message); } @@ -1257,7 +1255,7 @@ public class Wechat { // 上传媒体文件 String dataTicket = getCookieValue("webwx_data_ticket"); - JSONObject result = WebWeixinApiUtil.uploadMedia(httpClient, urlVersion, passTicket, baseRequest, loginUserName, toUserName, dataTicket, mediaData, mediaName, contentType); + JSONObject result = WebWeixinApiUtil.uploadMedia(httpClient, urlVersion, passTicket, baseRequest, loginUserName, toUserName, dataTicket, mediaData, mediaName, contentType, MediaType.PICTURE); if (result == null) { return null; } @@ -1284,7 +1282,7 @@ public class Wechat { message.setLocalID(msgId); message.setMediaId(mediaId); message.setToUserName(toUserName); - message.setType(MsgTypeEnum.IMAGE_MSG.getCode()); + message.setType(MsgType.IMAGE_MSG.getCode()); result = WebWeixinApiUtil.sendImageMsg(httpClient, urlVersion, passTicket, baseRequest, message); return result; @@ -1433,4 +1431,196 @@ public class Wechat { byte[] mediaData = FileUtil.getBytes(image); return sendImage(userName, nickName, remarkName, mediaData, image.getName(), contentType); } + + /** + * 发送视频消息 + * + * @param userName 用户名(加密的) + * @param mediaData 媒体文件数据 + * @param mediaName 媒体文件名 + * @param contentType 媒体文件类型 + * @return 返回数据 + */ + public JSONObject sendVideo(String userName, byte[] mediaData, String mediaName, ContentType contentType) { + String loginUserName = getLoginUserName(false); + String toUserName = StringUtil.isEmpty(userName) ? loginUserName : userName; + BaseRequest baseRequest = new BaseRequest(wxsid, skey, wxuin); + + // 上传媒体文件 + String dataTicket = getCookieValue("webwx_data_ticket"); + JSONObject result = WebWeixinApiUtil.uploadMedia(httpClient, urlVersion, passTicket, baseRequest, loginUserName, toUserName, dataTicket, mediaData, mediaName, contentType, MediaType.VIDEO); + if (result == null) { + return null; + } + JSONObject br = result.getJSONObject("BaseResponse"); + if (br == null) { + return result; + } + int ret = br.getIntValue("Ret"); + if (ret != 0) { + return result; + } + + String mediaId = result.getString("MediaId"); + if (StringUtil.isEmpty(mediaId)) { + return result; + } + + // 发送视频消息 + String msgId = WechatUtil.createMsgId(); + MediaMessage message = new MediaMessage(); + message.setClientMsgId(msgId); + message.setContent(""); + message.setFromUserName(loginUserName); + message.setLocalID(msgId); + message.setMediaId(mediaId); + message.setToUserName(toUserName); + message.setType(MsgType.VIDEO_CALL_MSG.getCode()); + result = WebWeixinApiUtil.sendVideoMsg(httpClient, urlVersion, baseRequest, message); + + return result; + } + + /** + * 发送视频消息 + * + * @param userName 用户名(加密的) + * @param video 视频文件 + * @return 返回数据 + */ + public JSONObject sendVideo(String userName, File video) { + ContentType contentType = FileUtil.getContentBody(video); + byte[] mediaData = FileUtil.getBytes(video); + return sendVideo(userName, mediaData, video.getName(), contentType); + } + + /** + * 发送视频消息(根据昵称) + * + * @param nickName 昵称 + * @param mediaData 媒体文件数据 + * @param mediaName 媒体文件名 + * @param contentType 媒体文件类型 + * @return 返回数据 + */ + public JSONObject sendVideoToNickName(String nickName, byte[] mediaData, String mediaName, ContentType contentType) { + if (StringUtil.isEmpty(nickName)) { + return sendVideo(null, mediaData, mediaName, contentType); + } + + UserInfo userInfo = getContactByNickName(false, nickName); + if (userInfo == null) { + return null; + } + + String userName = userInfo.getUserName(); + if (StringUtil.isEmpty(userName)) { + return null; + } + + return sendVideo(userName, mediaData, mediaName, contentType); + } + + /** + * 发送视频消息(根据昵称) + * + * @param nickName 昵称 + * @param video 视频文件 + * @return 返回数据 + */ + public JSONObject sendVideoToNickName(String nickName, File video) { + ContentType contentType = FileUtil.getContentBody(video); + byte[] mediaData = FileUtil.getBytes(video); + return sendVideoToNickName(nickName, mediaData, video.getName(), contentType); + } + + /** + * 发送视频消息(根据备注名) + * + * @param remarkName 备注名 + * @param mediaData 媒体文件数据 + * @param mediaName 媒体文件名 + * @param contentType 媒体文件类型 + * @return 返回数据 + */ + public JSONObject sendVideoToRemarkName(String remarkName, byte[] mediaData, String mediaName, ContentType contentType) { + if (StringUtil.isEmpty(remarkName)) { + return sendVideo(null, mediaData, mediaName, contentType); + } + + UserInfo userInfo = getContactByRemarkName(false, remarkName); + if (userInfo == null) { + return null; + } + + String userName = userInfo.getUserName(); + if (StringUtil.isEmpty(userName)) { + return null; + } + + return sendVideo(userName, mediaData, mediaName, contentType); + } + + /** + * 发送视频消息(根据备注名) + * + * @param remarkName 备注名 + * @param video 视频文件 + * @return 返回数据 + */ + public JSONObject sendVideoToRemarkName(String remarkName, File video) { + ContentType contentType = FileUtil.getContentBody(video); + byte[] mediaData = FileUtil.getBytes(video); + return sendVideoToRemarkName(remarkName, mediaData, video.getName(), contentType); + } + + /** + * 发送视频消息(根据多种名称) + * + * @param userName 用户名(加密的) + * @param nickName 昵称 + * @param remarkName 备注名 + * @param mediaData 媒体文件数据 + * @param mediaName 媒体文件名 + * @param contentType 媒体文件类型 + * @return 返回数据 + */ + public JSONObject sendVideo(String userName, String nickName, String remarkName, byte[] mediaData, String mediaName, ContentType contentType) { + UserInfo userInfo; + + if (StringUtil.isNotEmpty(userName)) { + return sendVideo(userName, mediaData, mediaName, contentType); + } else if (StringUtil.isNotEmpty(nickName)) { + userInfo = getContactByNickName(false, nickName); + } else if (StringUtil.isNotEmpty(remarkName)) { + userInfo = getContactByRemarkName(false, remarkName); + } else { + String loginUserName = getLoginUserName(false); + return sendVideo(loginUserName, mediaData, mediaName, contentType); + } + + if (userInfo == null) { + return null; + } + userName = userInfo.getUserName(); + if (StringUtil.isEmpty(userName)) { + return null; + } + return sendVideo(userName, mediaData, mediaName, contentType); + } + + /** + * 发送视频消息(根据多种名称) + * + * @param userName 用户名(加密的) + * @param nickName 昵称 + * @param remarkName 备注名 + * @param video 视频文件 + * @return 返回数据 + */ + public JSONObject sendVideo(String userName, String nickName, String remarkName, File video) { + ContentType contentType = FileUtil.getContentBody(video); + byte[] mediaData = FileUtil.getBytes(video); + return sendVideo(userName, nickName, remarkName, mediaData, video.getName(), contentType); + } } diff --git a/src/main/java/com/hotlcc/wechat4j/enums/ExitTypeEnum.java b/src/main/java/com/hotlcc/wechat4j/enums/ExitType.java similarity index 69% rename from src/main/java/com/hotlcc/wechat4j/enums/ExitTypeEnum.java rename to src/main/java/com/hotlcc/wechat4j/enums/ExitType.java index ded660c..c65b6d4 100644 --- a/src/main/java/com/hotlcc/wechat4j/enums/ExitTypeEnum.java +++ b/src/main/java/com/hotlcc/wechat4j/enums/ExitType.java @@ -1,19 +1,17 @@ package com.hotlcc.wechat4j.enums; +import lombok.AllArgsConstructor; + /** * 微信退出类型 * * @author Allen */ -public enum ExitTypeEnum { +@AllArgsConstructor +public enum ExitType { ERROR_EXIT("错误退出"), LOCAL_EXIT("本地退出"), REMOTE_EXIT("远程退出"); private String desc; - - ExitTypeEnum(String desc) { - this.desc = desc; - } - } diff --git a/src/main/java/com/hotlcc/wechat4j/enums/LoginTipEnum.java b/src/main/java/com/hotlcc/wechat4j/enums/LoginTip.java similarity index 62% rename from src/main/java/com/hotlcc/wechat4j/enums/LoginTipEnum.java rename to src/main/java/com/hotlcc/wechat4j/enums/LoginTip.java index aa05a3f..24a821d 100644 --- a/src/main/java/com/hotlcc/wechat4j/enums/LoginTipEnum.java +++ b/src/main/java/com/hotlcc/wechat4j/enums/LoginTip.java @@ -1,27 +1,23 @@ package com.hotlcc.wechat4j.enums; +import lombok.AllArgsConstructor; +import lombok.Getter; + /** * 等待确认登录的tip * * @author Allen */ @SuppressWarnings("unused") -public enum LoginTipEnum { +@Getter +@AllArgsConstructor +public enum LoginTip { TIP_0(0, "扫码登录"), TIP_1(1, "确认登录"); private int code; private String desc; - LoginTipEnum(int code, String desc) { - this.code = code; - this.desc = desc; - } - - public int getCode() { - return code; - } - @Override public String toString() { return code + ""; diff --git a/src/main/java/com/hotlcc/wechat4j/enums/MediaType.java b/src/main/java/com/hotlcc/wechat4j/enums/MediaType.java new file mode 100644 index 0000000..272bdc6 --- /dev/null +++ b/src/main/java/com/hotlcc/wechat4j/enums/MediaType.java @@ -0,0 +1,22 @@ +package com.hotlcc.wechat4j.enums; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +/** + * @author Allen + * @version 1.0 + * @date 2019/4/17 9:51 + */ +@Getter +@AllArgsConstructor +public enum MediaType { + PICTURE(4, "pic"), + VIDEO(4, "video"); + + public static String REQUEST_KEY = "mediatype"; + public static String REQUEST_JSON_KEY = "MediaType"; + + private Integer code; + private String value; +} diff --git a/src/main/java/com/hotlcc/wechat4j/enums/MsgTypeEnum.java b/src/main/java/com/hotlcc/wechat4j/enums/MsgType.java similarity index 78% rename from src/main/java/com/hotlcc/wechat4j/enums/MsgTypeEnum.java rename to src/main/java/com/hotlcc/wechat4j/enums/MsgType.java index cd39225..9e43499 100644 --- a/src/main/java/com/hotlcc/wechat4j/enums/MsgTypeEnum.java +++ b/src/main/java/com/hotlcc/wechat4j/enums/MsgType.java @@ -1,12 +1,17 @@ package com.hotlcc.wechat4j.enums; +import lombok.AllArgsConstructor; +import lombok.Getter; + /** * 消息类型enum * * @author Allen */ @SuppressWarnings({"unused"}) -public enum MsgTypeEnum { +@AllArgsConstructor +@Getter +public enum MsgType { TEXT_MSG(1, "文本消息"), IMAGE_MSG(3, "图片消息"), VOICE_MSG(34, "语音消息"), @@ -26,19 +31,6 @@ public enum MsgTypeEnum { SYSTEM_MSG(10000, "系统消息"), WITHDRAW_MSG(10002, "撤回消息"); - MsgTypeEnum(int code, String desc) { - this.code = code; - this.desc = desc; - } - private int code; private String desc; - - public int getCode() { - return code; - } - - public String getDesc() { - return desc; - } } diff --git a/src/main/java/com/hotlcc/wechat4j/enums/OperatingSystem.java b/src/main/java/com/hotlcc/wechat4j/enums/OperatingSystem.java new file mode 100644 index 0000000..d820d92 --- /dev/null +++ b/src/main/java/com/hotlcc/wechat4j/enums/OperatingSystem.java @@ -0,0 +1,35 @@ +package com.hotlcc.wechat4j.enums; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +/** + * 操作系统enum + * + * @author Allen + */ +@Getter +@AllArgsConstructor +public enum OperatingSystem { + DARWIN("darwin"), + WINDOWS("windows"), + LINUX("linux"), + MAC_OS("mac"), + OTHER("other"); + + private String value; + + public static OperatingSystem currentOperatingSystem() { + String osName = System.getProperty("os.name").toLowerCase(); + if (osName.contains(OperatingSystem.DARWIN.getValue())) { + return OperatingSystem.DARWIN; + } else if (osName.contains(OperatingSystem.WINDOWS.getValue())) { + return OperatingSystem.WINDOWS; + } else if (osName.contains(OperatingSystem.LINUX.getValue())) { + return OperatingSystem.LINUX; + } else if (osName.contains(OperatingSystem.MAC_OS.getValue())) { + return OperatingSystem.MAC_OS; + } + return OperatingSystem.OTHER; + } +} diff --git a/src/main/java/com/hotlcc/wechat4j/enums/OperatingSystemEnum.java b/src/main/java/com/hotlcc/wechat4j/enums/OperatingSystemEnum.java deleted file mode 100644 index 0c64c28..0000000 --- a/src/main/java/com/hotlcc/wechat4j/enums/OperatingSystemEnum.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.hotlcc.wechat4j.enums; - -/** - * 操作系统enum - * - * @author Allen - */ -public enum OperatingSystemEnum { - DARWIN("darwin"), - WINDOWS("windows"), - LINUX("linux"), - MAC_OS("mac"), - OTHER("other"); - - private String value; - - public String getValue() { - return value; - } - - OperatingSystemEnum(String value) { - this.value = value; - } - - public static OperatingSystemEnum currentOperatingSystem() { - String osName = System.getProperty("os.name").toLowerCase(); - if (osName.indexOf(OperatingSystemEnum.DARWIN.getValue()) >= 0) { - return OperatingSystemEnum.DARWIN; - } else if (osName.indexOf(OperatingSystemEnum.WINDOWS.getValue()) >= 0) { - return OperatingSystemEnum.WINDOWS; - } else if (osName.indexOf(OperatingSystemEnum.LINUX.getValue()) >= 0) { - return OperatingSystemEnum.LINUX; - } else if (osName.indexOf(OperatingSystemEnum.MAC_OS.getValue()) >= 0) { - return OperatingSystemEnum.MAC_OS; - } - return OperatingSystemEnum.OTHER; - } -} diff --git a/src/main/java/com/hotlcc/wechat4j/enums/RetcodeEnum.java b/src/main/java/com/hotlcc/wechat4j/enums/Retcode.java similarity index 54% rename from src/main/java/com/hotlcc/wechat4j/enums/RetcodeEnum.java rename to src/main/java/com/hotlcc/wechat4j/enums/Retcode.java index 88ef71d..51566b4 100644 --- a/src/main/java/com/hotlcc/wechat4j/enums/RetcodeEnum.java +++ b/src/main/java/com/hotlcc/wechat4j/enums/Retcode.java @@ -1,11 +1,16 @@ package com.hotlcc.wechat4j.enums; +import lombok.AllArgsConstructor; +import lombok.Getter; + /** * Ret代码 * * @author Allen */ -public enum RetcodeEnum { +@AllArgsConstructor +@Getter +public enum Retcode { RECODE_0(0, "正常"), RECODE_1100(1100, "失败/登出微信"), RECODE_1101(1101, "从其它设备登录微信"); @@ -13,18 +18,9 @@ public enum RetcodeEnum { private int code; private String desc; - RetcodeEnum(int code, String desc) { - this.code = code; - this.desc = desc; - } - - public int getCode() { - return code; - } - - public static RetcodeEnum valueOf(int code) { - RetcodeEnum[] es = values(); - for (RetcodeEnum e : es) { + public static Retcode valueOf(int code) { + Retcode[] es = values(); + for (Retcode e : es) { if (e.code == code) { return e; } diff --git a/src/main/java/com/hotlcc/wechat4j/enums/SelectorEnum.java b/src/main/java/com/hotlcc/wechat4j/enums/Selector.java similarity index 65% rename from src/main/java/com/hotlcc/wechat4j/enums/SelectorEnum.java rename to src/main/java/com/hotlcc/wechat4j/enums/Selector.java index 7115c6d..f8336ae 100644 --- a/src/main/java/com/hotlcc/wechat4j/enums/SelectorEnum.java +++ b/src/main/java/com/hotlcc/wechat4j/enums/Selector.java @@ -1,11 +1,14 @@ package com.hotlcc.wechat4j.enums; +import lombok.AllArgsConstructor; + /** * Selector代码 * * @author Allen */ -public enum SelectorEnum { +@AllArgsConstructor +public enum Selector { SELECTOR_0(0, "正常"), SELECTOR_2(2, "有新消息"), SELECTOR_4(4, "目前发现修改了联系人备注会出现"), @@ -15,14 +18,9 @@ public enum SelectorEnum { private int code; private String desc; - SelectorEnum(int code, String desc) { - this.code = code; - this.desc = desc; - } - - public static SelectorEnum valueOf(int code) { - SelectorEnum[] es = values(); - for (SelectorEnum e : es) { + public static Selector valueOf(int code) { + Selector[] es = values(); + for (Selector e : es) { if (e.code == code) { return e; } diff --git a/src/main/java/com/hotlcc/wechat4j/handler/ExitEventHandler.java b/src/main/java/com/hotlcc/wechat4j/handler/ExitEventHandler.java index ff30337..4e57f75 100644 --- a/src/main/java/com/hotlcc/wechat4j/handler/ExitEventHandler.java +++ b/src/main/java/com/hotlcc/wechat4j/handler/ExitEventHandler.java @@ -1,7 +1,7 @@ package com.hotlcc.wechat4j.handler; import com.hotlcc.wechat4j.Wechat; -import com.hotlcc.wechat4j.enums.ExitTypeEnum; +import com.hotlcc.wechat4j.enums.ExitType; /** * 退出事件处理器 @@ -16,7 +16,7 @@ public interface ExitEventHandler { * @param type 退出类型 * @param t 异常 */ - void handleAllType(Wechat wechat, ExitTypeEnum type, Throwable t); + void handleAllType(Wechat wechat, ExitType type, Throwable t); /** * 针对错误导致的退出事件 diff --git a/src/main/java/com/hotlcc/wechat4j/util/QRCodeUtil.java b/src/main/java/com/hotlcc/wechat4j/util/QRCodeUtil.java index df64c8c..7da9644 100644 --- a/src/main/java/com/hotlcc/wechat4j/util/QRCodeUtil.java +++ b/src/main/java/com/hotlcc/wechat4j/util/QRCodeUtil.java @@ -6,7 +6,7 @@ import com.google.zxing.NotFoundException; import com.google.zxing.client.j2se.BufferedImageLuminanceSource; import com.google.zxing.common.BitMatrix; import com.google.zxing.common.HybridBinarizer; -import com.hotlcc.wechat4j.enums.OperatingSystemEnum; +import com.hotlcc.wechat4j.enums.OperatingSystem; import lombok.extern.slf4j.Slf4j; import javax.imageio.ImageIO; @@ -269,7 +269,7 @@ public final class QRCodeUtil { * @param data 二维码图片的字节数据 */ public static void openQRCodeImage(byte[] data) { - OperatingSystemEnum os = OperatingSystemEnum.currentOperatingSystem(); + OperatingSystem os = OperatingSystem.currentOperatingSystem(); Runtime runtime; File tmp; switch (os) { diff --git a/src/main/java/com/hotlcc/wechat4j/util/WebWeixinApiUtil.java b/src/main/java/com/hotlcc/wechat4j/util/WebWeixinApiUtil.java index 1ec8ae6..8782739 100644 --- a/src/main/java/com/hotlcc/wechat4j/util/WebWeixinApiUtil.java +++ b/src/main/java/com/hotlcc/wechat4j/util/WebWeixinApiUtil.java @@ -2,7 +2,8 @@ package com.hotlcc.wechat4j.util; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; -import com.hotlcc.wechat4j.enums.LoginTipEnum; +import com.hotlcc.wechat4j.enums.LoginTip; +import com.hotlcc.wechat4j.enums.MediaType; import com.hotlcc.wechat4j.model.BaseRequest; import com.hotlcc.wechat4j.model.MediaMessage; import com.hotlcc.wechat4j.model.WxMessage; @@ -156,7 +157,7 @@ public final class WebWeixinApiUtil { * @return 返回数据 */ public static JSONObject getRedirectUri(HttpClient httpClient, - LoginTipEnum tip, + LoginTip tip, String uuid) { try { long millis = System.currentTimeMillis(); @@ -672,6 +673,7 @@ public final class WebWeixinApiUtil { * @param mediaData 媒体文件二进制数据 * @param mediaName 媒体文件名称 * @param contentType 媒体文件类型 + * @param mediaType 媒体类型 * @return 返回数据 */ public static JSONObject uploadMedia(HttpClient httpClient, @@ -683,7 +685,8 @@ public final class WebWeixinApiUtil { String dataTicket, byte[] mediaData, String mediaName, - ContentType contentType) { + ContentType contentType, + MediaType mediaType) { try { String url = new ST(PropertiesUtil.getProperty("webwx-url.uploadmedia_url")) .add("urlVersion", urlVersion) @@ -702,7 +705,7 @@ public final class WebWeixinApiUtil { uploadmediarequest.put("TotalLen", mediaLength); uploadmediarequest.put("StartPos", 0); uploadmediarequest.put("DataLen", mediaLength); - uploadmediarequest.put("MediaType", 4); + uploadmediarequest.put(MediaType.REQUEST_JSON_KEY, mediaType.getCode()); uploadmediarequest.put("FromUserName", fromUserName); uploadmediarequest.put("ToUserName", toUserName); uploadmediarequest.put("FileMd5", DigestUtils.md5Hex(mediaData)); @@ -721,6 +724,7 @@ public final class WebWeixinApiUtil { .setMode(HttpMultipartMode.BROWSER_COMPATIBLE) .addTextBody("chunks", String.valueOf(chunks)) .addTextBody("chunk", String.valueOf(chunk)) + .addTextBody(MediaType.REQUEST_KEY, mediaType.getValue(), ContentType.TEXT_PLAIN) .addTextBody("uploadmediarequest", uploadmediarequest.toJSONString(), ContentType.TEXT_PLAIN) .addTextBody("webwx_data_ticket", dataTicket, ContentType.TEXT_PLAIN) .addTextBody("pass_ticket", passticket, ContentType.TEXT_PLAIN) @@ -805,4 +809,48 @@ public final class WebWeixinApiUtil { return null; } } + + /** + * 发送视频消息 + * + * @param httpClient http客户端 + * @param urlVersion url版本号 + * @param baseRequest BaseRequest + * @param message 消息 + * @return 返回数据 + */ + public static JSONObject sendVideoMsg(HttpClient httpClient, + String urlVersion, + BaseRequest baseRequest, + MediaMessage message) { + try { + String url = new ST(PropertiesUtil.getProperty("webwx-url.webwxsendvideomsg_url")) + .add("urlVersion", urlVersion) + .render(); + + HttpPost httpPost = new HttpPost(url); + httpPost.setHeader("Content-type", ContentType.APPLICATION_JSON.toString()); + + JSONObject paramJson = new JSONObject(); + paramJson.put("BaseRequest", baseRequest); + paramJson.put("Msg", message); + paramJson.put("Scene", 0); + HttpEntity paramEntity = new StringEntity(paramJson.toJSONString(), Consts.UTF_8); + httpPost.setEntity(paramEntity); + + HttpResponse response = httpClient.execute(httpPost); + int statusCode = response.getStatusLine().getStatusCode(); + if (HttpStatus.SC_OK != statusCode) { + throw new RuntimeException("响应失败(" + statusCode + ")"); + } + + HttpEntity entity = response.getEntity(); + String res = EntityUtils.toString(entity, Consts.UTF_8); + + return JSONObject.parseObject(res); + } catch (Exception e) { + log.error("发送视频消息异常", e); + return null; + } + } } diff --git a/src/main/resources/META-INF/wechat4j/webwx-url.properties b/src/main/resources/META-INF/wechat4j/webwx-url.properties index cce8015..d686c57 100644 --- a/src/main/resources/META-INF/wechat4j/webwx-url.properties +++ b/src/main/resources/META-INF/wechat4j/webwx-url.properties @@ -31,4 +31,6 @@ webwx-url.webwxsendmsg_url=https://wx.qq.com/cgi-bin/mmwebwx-bin/web ## 4.3、上传媒体文件 webwx-url.uploadmedia_url=https://file.wx.qq.com/cgi-bin/mmwebwx-bin/webwxuploadmedia?f=json ## 4.4、发送图片消息 -webwx-url.webwxsendmsgimg_url=https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxsendmsgimg?fun=async&f=json&lang=zh_CN&pass_ticket= \ No newline at end of file +webwx-url.webwxsendmsgimg_url=https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxsendmsgimg?fun=async&f=json&lang=zh_CN&pass_ticket= +## 4.5、发送视频消息 +webwx-url.webwxsendvideomsg_url=https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxsendvideomsg?fun=async&f=json \ No newline at end of file diff --git a/src/test/java/TestClass.java b/src/test/java/TestClass.java index fdd99da..bc9c395 100644 --- a/src/test/java/TestClass.java +++ b/src/test/java/TestClass.java @@ -3,6 +3,7 @@ import com.hotlcc.wechat4j.Wechat; import com.hotlcc.wechat4j.handler.ReceivedMsgHandler; import com.hotlcc.wechat4j.model.ReceivedMsg; import com.hotlcc.wechat4j.model.UserInfo; +import com.hotlcc.wechat4j.util.CommonUtil; import com.hotlcc.wechat4j.util.StringUtil; import org.junit.Before; import org.junit.Test; @@ -34,9 +35,13 @@ public class TestClass { @Test public void testSendImage() { - File file = new File("D:\\Downloads\\images\\6600e90b8b0ce2037a5291a7147ffd2b.jpeg"); - - JSONObject result = wechat.sendImage(null, file); + File file = null; + JSONObject result = null; + file = new File("C:\\Users\\Administrator\\Pictures\\壁纸\\9e5f4981099bcf351e0ec18c3654aced.jpg"); + result = wechat.sendImage(null, file); + file = new File("C:\\Users\\Administrator\\Videos\\手机QQ视频_20190416170016.mp4"); + result = wechat.sendVideo(null, file); System.out.println(result); + while (true) CommonUtil.threadSleep(5000); } } From 952040f6a6fb402e2082f3924f1ac4c1d49f7bdf Mon Sep 17 00:00:00 2001 From: Allen Date: Wed, 17 Apr 2019 10:19:19 +0800 Subject: [PATCH 4/4] =?UTF-8?q?[=E5=8D=87=E7=BA=A7=E7=89=88=E6=9C=AC]=200.?= =?UTF-8?q?2.3=20->=200.2.4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index f53f673..57013e9 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.hotlcc wechat4j - 0.2.3 + 0.2.4 wechat4j Wechat client for Java.