2
0
mirror of https://gitee.com/hotlcc/wechat4j.git synced 2025-06-08 11:34:07 +08:00
Merge pull request !8 from Allen/feature/20180914
This commit is contained in:
Allen 2018-09-18 14:43:15 +08:00
commit 5c9aee686e
24 changed files with 445 additions and 334 deletions

View File

@ -6,7 +6,7 @@
<groupId>com.hotlcc</groupId> <groupId>com.hotlcc</groupId>
<artifactId>wechat4j</artifactId> <artifactId>wechat4j</artifactId>
<version>0.2.0</version> <version>0.2.1</version>
<name>wechat4j</name> <name>wechat4j</name>
<description>Wechat client for Java.</description> <description>Wechat client for Java.</description>

View File

@ -35,7 +35,7 @@ import java.util.concurrent.locks.ReentrantLock;
* *
* @author Allen * @author Allen
*/ */
@SuppressWarnings("Duplicates") @SuppressWarnings({"Duplicates", "unused"})
public class Wechat { public class Wechat {
private static Logger logger = LoggerFactory.getLogger(Wechat.class); private static Logger logger = LoggerFactory.getLogger(Wechat.class);
@ -82,6 +82,12 @@ public class Wechat {
this.webWeixinApi = webWeixinApi; this.webWeixinApi = webWeixinApi;
} }
/**
* 获取Cookie
*
* @param name key
* @return Cookie
*/
private Cookie getCookie(String name) { private Cookie getCookie(String name) {
List<Cookie> cookies = cookieStore.getCookies(); List<Cookie> cookies = cookieStore.getCookies();
if (cookies == null) { if (cookies == null) {
@ -95,6 +101,12 @@ public class Wechat {
return null; return null;
} }
/**
* 获取Cookie值
*
* @param name key
* @return Cookie值
*/
public String getCookieValue(String name) { public String getCookieValue(String name) {
Cookie cookie = getCookie(name); Cookie cookie = getCookie(name);
if (cookie == null) { if (cookie == null) {
@ -103,6 +115,11 @@ public class Wechat {
return cookie.getValue(); return cookie.getValue();
} }
/**
* 添加退出事件处理器
*
* @param handler 退出事件处理器
*/
public void addExitEventHandler(ExitEventHandler handler) { public void addExitEventHandler(ExitEventHandler handler) {
if (handler == null) { if (handler == null) {
return; return;
@ -114,6 +131,11 @@ public class Wechat {
exitEventHandlers.add(handler); exitEventHandlers.add(handler);
} }
/**
* 添加退出事件处理器
*
* @param handlers 退出事件处理器
*/
public void addExitEventHandler(Collection<ExitEventHandler> handlers) { public void addExitEventHandler(Collection<ExitEventHandler> handlers) {
if (handlers == null || handlers.isEmpty()) { if (handlers == null || handlers.isEmpty()) {
return; return;
@ -126,6 +148,11 @@ public class Wechat {
} }
} }
/**
* 添加接收消息处理器
*
* @param handler 接收消息处理器
*/
public void addReceivedMsgHandler(ReceivedMsgHandler handler) { public void addReceivedMsgHandler(ReceivedMsgHandler handler) {
if (handler == null) { if (handler == null) {
return; return;
@ -136,6 +163,11 @@ public class Wechat {
receivedMsgHandlers.add(handler); receivedMsgHandlers.add(handler);
} }
/**
* 添加接收消息处理器
*
* @param handlers 接收消息处理器
*/
public void addReceivedMsgHandler(Collection<ReceivedMsgHandler> handlers) { public void addReceivedMsgHandler(Collection<ReceivedMsgHandler> handlers) {
if (handlers == null || handlers.isEmpty()) { if (handlers == null || handlers.isEmpty()) {
return; return;
@ -148,6 +180,12 @@ public class Wechat {
} }
} }
/**
* 构建http客户端
*
* @param cookieStore Cookie保存
* @return http客户端
*/
private HttpClient buildHttpClient(CookieStore cookieStore) { private HttpClient buildHttpClient(CookieStore cookieStore) {
HttpRequestInterceptor interceptor = new HttpRequestInterceptor() { HttpRequestInterceptor interceptor = new HttpRequestInterceptor() {
@Override @Override
@ -474,7 +512,7 @@ public class Wechat {
return true; return true;
} }
JSONObject result = null; JSONObject result;
int time = PropertiesUtil.getIntValue("wechat4j.retry.time", 3); int time = PropertiesUtil.getIntValue("wechat4j.retry.time", 3);
// 2登录 // 2登录
@ -538,7 +576,7 @@ public class Wechat {
/** /**
* 自动登录 * 自动登录
* *
* @return * @return 成功状态
*/ */
public boolean autoLogin() { public boolean autoLogin() {
return autoLogin(null, false); return autoLogin(null, false);
@ -546,6 +584,8 @@ public class Wechat {
/** /**
* 退出登录 * 退出登录
*
* @param clearAllLoginInfo 是否清除全部登录信息
*/ */
public void logout(boolean clearAllLoginInfo) { public void logout(boolean clearAllLoginInfo) {
if (isOnline) { if (isOnline) {
@ -599,7 +639,7 @@ public class Wechat {
/** /**
* 判断在线状态 * 判断在线状态
* *
* @return * @return 是否在线
*/ */
public boolean isOnline() { public boolean isOnline() {
return isOnline; return isOnline;
@ -673,6 +713,9 @@ public class Wechat {
/** /**
* 处理退出事件 * 处理退出事件
*
* @param type 退出类型
* @param t 异常
*/ */
private void processExitEvent(ExitTypeEnum type, Throwable t) { private void processExitEvent(ExitTypeEnum type, Throwable t) {
try { try {
@ -719,7 +762,7 @@ public class Wechat {
/** /**
* 处理selector值 * 处理selector值
* *
* @param selector * @param selector selector值
*/ */
private void processSelector(int selector) { private void processSelector(int selector) {
try { try {
@ -751,8 +794,6 @@ public class Wechat {
/** /**
* 同步数据 * 同步数据
*
* @return
*/ */
private void webWxSync() { private void webWxSync() {
try { try {
@ -762,21 +803,21 @@ public class Wechat {
return; return;
} }
JSONObject BaseResponse = result.getJSONObject("BaseResponse"); JSONObject baseResponse = result.getJSONObject("BaseResponse");
if (BaseResponse == null) { if (baseResponse == null) {
logger.warn("同步接口返回数据格式错误"); logger.warn("同步接口返回数据格式错误");
return; return;
} }
int Ret = BaseResponse.getIntValue("Ret"); int ret = baseResponse.getIntValue("Ret");
if (Ret != RetcodeEnum.RECODE_0.getCode()) { if (ret != RetcodeEnum.RECODE_0.getCode()) {
logger.warn("同步接口返回错误代码:{}", Ret); logger.warn("同步接口返回错误代码:{}", ret);
return; return;
} }
//新消息处理 //新消息处理
JSONArray AddMsgList = result.getJSONArray("AddMsgList"); JSONArray addMsgList = result.getJSONArray("AddMsgList");
processNewMsg(AddMsgList); processNewMsg(addMsgList);
//更新SyncKey //更新SyncKey
try { try {
@ -793,15 +834,15 @@ public class Wechat {
/** /**
* 处理新消息 * 处理新消息
* *
* @param AddMsgList * @param addMsgList 消息列表
*/ */
private void processNewMsg(JSONArray AddMsgList) { private void processNewMsg(JSONArray addMsgList) {
try { try {
if (AddMsgList == null || AddMsgList.isEmpty()) { if (addMsgList == null || addMsgList.isEmpty()) {
return; return;
} }
int len = AddMsgList.size(); int len = addMsgList.size();
logger.debug("收到{}条新消息", len); logger.debug("收到{}条新消息", len);
if (receivedMsgHandlers == null || receivedMsgHandlers.isEmpty()) { if (receivedMsgHandlers == null || receivedMsgHandlers.isEmpty()) {
@ -809,7 +850,7 @@ public class Wechat {
return; return;
} }
List<ReceivedMsg> receivedMsgList = ReceivedMsg.valueOf(AddMsgList); List<ReceivedMsg> receivedMsgList = ReceivedMsg.valueOf(addMsgList);
for (ReceivedMsg receivedMsg : receivedMsgList) { for (ReceivedMsg receivedMsg : receivedMsgList) {
for (ReceivedMsgHandler handler : receivedMsgHandlers) { for (ReceivedMsgHandler handler : receivedMsgHandlers) {
if (handler != null) { if (handler != null) {
@ -834,7 +875,7 @@ public class Wechat {
/** /**
* 获取登录用户对象 * 获取登录用户对象
* *
* @return * @return 登录用户对象
*/ */
public UserInfo getLoginUser(boolean update) { public UserInfo getLoginUser(boolean update) {
if (loginUser == null || update) { if (loginUser == null || update) {
@ -843,13 +884,13 @@ public class Wechat {
return loginUser; return loginUser;
} }
JSONObject BaseResponse = result.getJSONObject("BaseResponse"); JSONObject baseResponse = result.getJSONObject("BaseResponse");
if (result == null) { if (baseResponse == null) {
return loginUser; return loginUser;
} }
int Ret = BaseResponse.getIntValue("Ret"); int ret = baseResponse.getIntValue("Ret");
if (Ret != 0) { if (ret != 0) {
return loginUser; return loginUser;
} }
@ -874,7 +915,7 @@ public class Wechat {
/** /**
* 获取登录用户名 * 获取登录用户名
* *
* @return * @return 登录用户的用户名加密的
*/ */
public String getLoginUserName(boolean update) { public String getLoginUserName(boolean update) {
UserInfo loginUser = getLoginUser(update); UserInfo loginUser = getLoginUser(update);
@ -891,7 +932,7 @@ public class Wechat {
/** /**
* 获取登录用户的昵称 * 获取登录用户的昵称
* *
* @return * @return 登录用户的昵称
*/ */
public String getLoginUserNickName(boolean update) { public String getLoginUserNickName(boolean update) {
UserInfo loginUser = getLoginUser(update); UserInfo loginUser = getLoginUser(update);
@ -908,8 +949,8 @@ public class Wechat {
/** /**
* 获取SyncKey * 获取SyncKey
* *
* @param update * @param update 是否强制更新
* @return * @return 返回数据
*/ */
private JSONObject getSyncKey(boolean update) { private JSONObject getSyncKey(boolean update) {
if (syncKey == null || update) { if (syncKey == null || update) {
@ -918,13 +959,13 @@ public class Wechat {
return syncKey; return syncKey;
} }
JSONObject BaseResponse = result.getJSONObject("BaseResponse"); JSONObject baseResponse = result.getJSONObject("BaseResponse");
if (result == null) { if (baseResponse == null) {
return syncKey; return syncKey;
} }
int Ret = BaseResponse.getIntValue("Ret"); int ret = baseResponse.getIntValue("Ret");
if (Ret != 0) { if (ret != 0) {
return syncKey; return syncKey;
} }
@ -945,22 +986,22 @@ public class Wechat {
/** /**
* 获取SyncKey的List * 获取SyncKey的List
* *
* @param update * @param update 是否强制更新
* @return * @return 返回数据
*/ */
private JSONArray getSyncKeyList(boolean update) { private JSONArray getSyncKeyList(boolean update) {
JSONObject SyncKey = getSyncKey(update); JSONObject syncKey = getSyncKey(update);
if (SyncKey == null) { if (syncKey == null) {
return null; return null;
} }
return SyncKey.getJSONArray("List"); return syncKey.getJSONArray("List");
} }
/** /**
* 获取联系人列表 * 获取联系人列表
* *
* @param update * @param update 是否强制更新
* @return * @return 返回数据
*/ */
public List<UserInfo> getContactList(boolean update) { public List<UserInfo> getContactList(boolean update) {
if (contactList == null || update) { if (contactList == null || update) {
@ -969,13 +1010,13 @@ public class Wechat {
return contactList; return contactList;
} }
JSONObject BaseResponse = result.getJSONObject("BaseResponse"); JSONObject baseResponse = result.getJSONObject("BaseResponse");
if (BaseResponse == null) { if (baseResponse == null) {
return contactList; return contactList;
} }
String Ret = BaseResponse.getString("Ret"); String ret = baseResponse.getString("Ret");
if (!"0".equals(Ret)) { if (!"0".equals(ret)) {
return contactList; return contactList;
} }
@ -1000,9 +1041,9 @@ public class Wechat {
/** /**
* 根据UserName获取联系人信息 * 根据UserName获取联系人信息
* *
* @param update * @param update 是否强制更新
* @param userName * @param userName 用户名加密的
* @return * @return 返回数据
*/ */
public UserInfo getContactByUserName(boolean update, String userName) { public UserInfo getContactByUserName(boolean update, String userName) {
if (StringUtil.isEmpty(userName)) { if (StringUtil.isEmpty(userName)) {
@ -1034,9 +1075,9 @@ public class Wechat {
/** /**
* 根据NickName获取联系人信息 * 根据NickName获取联系人信息
* *
* @param update * @param update 是否强制更新
* @param nickName * @param nickName 昵称
* @return * @return 返回数据
*/ */
public UserInfo getContactByNickName(boolean update, String nickName) { public UserInfo getContactByNickName(boolean update, String nickName) {
if (StringUtil.isEmpty(nickName)) { if (StringUtil.isEmpty(nickName)) {
@ -1068,9 +1109,9 @@ public class Wechat {
/** /**
* 根据RemarkName获取联系人信息 * 根据RemarkName获取联系人信息
* *
* @param update * @param update 是否强制更新
* @param remarkName * @param remarkName 备注名
* @return * @return 返回数据
*/ */
public UserInfo getContactByRemarkName(boolean update, String remarkName) { public UserInfo getContactByRemarkName(boolean update, String remarkName) {
if (StringUtil.isEmpty(remarkName)) { if (StringUtil.isEmpty(remarkName)) {
@ -1102,9 +1143,9 @@ public class Wechat {
/** /**
* 发送文本消息 * 发送文本消息
* *
* @param userName * @param userName 用户名加密的
* @param content * @param content 文本消息内容
* @return * @return 返回数据
*/ */
public JSONObject sendText(String userName, String content) { public JSONObject sendText(String userName, String content) {
BaseRequest baseRequest = new BaseRequest(wxsid, skey, wxuin); BaseRequest baseRequest = new BaseRequest(wxsid, skey, wxuin);
@ -1123,17 +1164,15 @@ public class Wechat {
} }
message.setType(MsgTypeEnum.TEXT_MSG.getCode()); message.setType(MsgTypeEnum.TEXT_MSG.getCode());
JSONObject result = webWeixinApi.sendMsg(httpClient, urlVersion, passTicket, baseRequest, message); return webWeixinApi.sendMsg(httpClient, urlVersion, passTicket, baseRequest, message);
return result;
} }
/** /**
* 发送文本消息根据昵称 * 发送文本消息根据昵称
* *
* @param nickName * @param nickName 昵称
* @param content * @param content 文本消息内容
* @return * @return 返回数据
*/ */
public JSONObject sendTextToNickName(String nickName, String content) { public JSONObject sendTextToNickName(String nickName, String content) {
if (StringUtil.isEmpty(nickName)) { if (StringUtil.isEmpty(nickName)) {
@ -1156,9 +1195,9 @@ public class Wechat {
/** /**
* 发送文本消息根据备注名 * 发送文本消息根据备注名
* *
* @param remarkName * @param remarkName 备注
* @param content * @param content 文本消息内容
* @return * @return 返回数据
*/ */
public JSONObject sendTextToRemarkName(String remarkName, String content) { public JSONObject sendTextToRemarkName(String remarkName, String content) {
if (StringUtil.isEmpty(remarkName)) { if (StringUtil.isEmpty(remarkName)) {
@ -1181,14 +1220,14 @@ public class Wechat {
/** /**
* 发送文本消息根据多种名称 * 发送文本消息根据多种名称
* *
* @param userName * @param userName 用户名加密的
* @param nickName * @param nickName 昵称
* @param remarkName * @param remarkName 备注
* @param content * @param content 文本消息内容
* @return * @return 返回数据
*/ */
public JSONObject sendText(String userName, String nickName, String remarkName, String content) { public JSONObject sendText(String userName, String nickName, String remarkName, String content) {
UserInfo userInfo = null; UserInfo userInfo;
if (StringUtil.isNotEmpty(userName)) { if (StringUtil.isNotEmpty(userName)) {
return sendText(content, userName); return sendText(content, userName);
@ -1214,11 +1253,11 @@ public class Wechat {
/** /**
* 发送图片消息 * 发送图片消息
* *
* @param userName * @param userName 用户名加密的
* @param mediaData * @param mediaData 媒体文件数据
* @param mediaName * @param mediaName 媒体文件名
* @param contentType * @param contentType 媒体文件类型
* @return * @return 返回数据
*/ */
public JSONObject sendImage(String userName, byte[] mediaData, String mediaName, ContentType contentType) { public JSONObject sendImage(String userName, byte[] mediaData, String mediaName, ContentType contentType) {
String loginUserName = getLoginUserName(false); String loginUserName = getLoginUserName(false);
@ -1231,17 +1270,17 @@ public class Wechat {
if (result == null) { if (result == null) {
return null; return null;
} }
JSONObject BaseResponse = result.getJSONObject("BaseResponse"); JSONObject br = result.getJSONObject("BaseResponse");
if (BaseResponse == null) { if (br == null) {
return result; return result;
} }
int Ret = BaseResponse.getIntValue("Ret"); int ret = br.getIntValue("Ret");
if (Ret != 0) { if (ret != 0) {
return result; return result;
} }
String MediaId = result.getString("MediaId"); String mediaId = result.getString("MediaId");
if (StringUtil.isEmpty(MediaId)) { if (StringUtil.isEmpty(mediaId)) {
return result; return result;
} }
@ -1252,7 +1291,7 @@ public class Wechat {
message.setContent(""); message.setContent("");
message.setFromUserName(loginUserName); message.setFromUserName(loginUserName);
message.setLocalID(msgId); message.setLocalID(msgId);
message.setMediaId(MediaId); message.setMediaId(mediaId);
message.setToUserName(toUserName); message.setToUserName(toUserName);
message.setType(MsgTypeEnum.IMAGE_MSG.getCode()); message.setType(MsgTypeEnum.IMAGE_MSG.getCode());
result = webWeixinApi.sendImageMsg(httpClient, urlVersion, passTicket, baseRequest, message); result = webWeixinApi.sendImageMsg(httpClient, urlVersion, passTicket, baseRequest, message);
@ -1263,9 +1302,9 @@ public class Wechat {
/** /**
* 发送图片消息 * 发送图片消息
* *
* @param userName * @param userName 用户名加密的
* @param image * @param image 图片文件
* @return * @return 返回数据
*/ */
public JSONObject sendImage(String userName, File image) { public JSONObject sendImage(String userName, File image) {
ContentType contentType = FileUtil.getContentBody(image); ContentType contentType = FileUtil.getContentBody(image);
@ -1276,11 +1315,11 @@ public class Wechat {
/** /**
* 发送图片消息根据昵称 * 发送图片消息根据昵称
* *
* @param nickName * @param nickName 昵称
* @param mediaData * @param mediaData 媒体文件数据
* @param mediaName * @param mediaName 媒体文件名
* @param contentType * @param contentType 媒体文件类型
* @return * @return 返回数据
*/ */
public JSONObject sendImageToNickName(String nickName, byte[] mediaData, String mediaName, ContentType contentType) { public JSONObject sendImageToNickName(String nickName, byte[] mediaData, String mediaName, ContentType contentType) {
if (StringUtil.isEmpty(nickName)) { if (StringUtil.isEmpty(nickName)) {
@ -1303,9 +1342,9 @@ public class Wechat {
/** /**
* 发送图片消息根据昵称 * 发送图片消息根据昵称
* *
* @param nickName * @param nickName 昵称
* @param image * @param image 图片文件
* @return * @return 返回数据
*/ */
public JSONObject sendImageToNickName(String nickName, File image) { public JSONObject sendImageToNickName(String nickName, File image) {
ContentType contentType = FileUtil.getContentBody(image); ContentType contentType = FileUtil.getContentBody(image);
@ -1316,11 +1355,11 @@ public class Wechat {
/** /**
* 发送图片消息根据备注名 * 发送图片消息根据备注名
* *
* @param remarkName * @param remarkName 备注名
* @param mediaData * @param mediaData 媒体文件数据
* @param mediaName * @param mediaName 媒体文件名
* @param contentType * @param contentType 媒体文件类型
* @return * @return 返回数据
*/ */
public JSONObject sendImageToRemarkName(String remarkName, byte[] mediaData, String mediaName, ContentType contentType) { public JSONObject sendImageToRemarkName(String remarkName, byte[] mediaData, String mediaName, ContentType contentType) {
if (StringUtil.isEmpty(remarkName)) { if (StringUtil.isEmpty(remarkName)) {
@ -1343,9 +1382,9 @@ public class Wechat {
/** /**
* 发送图片消息根据备注名 * 发送图片消息根据备注名
* *
* @param remarkName * @param remarkName 备注名
* @param image * @param image 图片文件
* @return * @return 返回数据
*/ */
public JSONObject sendImageToRemarkName(String remarkName, File image) { public JSONObject sendImageToRemarkName(String remarkName, File image) {
ContentType contentType = FileUtil.getContentBody(image); ContentType contentType = FileUtil.getContentBody(image);
@ -1356,17 +1395,17 @@ public class Wechat {
/** /**
* 发送图片消息根据多种名称 * 发送图片消息根据多种名称
* *
* @param userName * @param userName 用户名加密的
* @param nickName * @param nickName 昵称
* @param remarkName * @param remarkName 备注名
* @param mediaData * @param mediaData 媒体文件数据
* @param mediaName * @param mediaName 媒体文件名
* @param contentType * @param contentType 媒体文件类型
* @return * @return 返回数据
*/ */
public JSONObject sendImage(String userName, String nickName, String remarkName public JSONObject sendImage(String userName, String nickName, String remarkName
, byte[] mediaData, String mediaName, ContentType contentType) { , byte[] mediaData, String mediaName, ContentType contentType) {
UserInfo userInfo = null; UserInfo userInfo;
if (StringUtil.isNotEmpty(userName)) { if (StringUtil.isNotEmpty(userName)) {
return sendImage(userName, mediaData, mediaName, contentType); return sendImage(userName, mediaData, mediaName, contentType);
@ -1392,11 +1431,11 @@ public class Wechat {
/** /**
* 发送图片消息根据多种名称 * 发送图片消息根据多种名称
* *
* @param userName * @param userName 用户名加密的
* @param nickName * @param nickName 昵称
* @param remarkName * @param remarkName 备注名
* @param image * @param image 图片文件
* @return * @return 返回数据
*/ */
public JSONObject sendImage(String userName, String nickName, String remarkName, File image) { public JSONObject sendImage(String userName, String nickName, String remarkName, File image) {
ContentType contentType = FileUtil.getContentBody(image); ContentType contentType = FileUtil.getContentBody(image);

View File

@ -39,7 +39,7 @@ import java.util.regex.Pattern;
* *
* @author Allen * @author Allen
*/ */
@SuppressWarnings("Duplicates") @SuppressWarnings({"Duplicates", "unused"})
public class WebWeixinApi { public class WebWeixinApi {
private static Logger logger = LoggerFactory.getLogger(WebWeixinApi.class); private static Logger logger = LoggerFactory.getLogger(WebWeixinApi.class);
@ -50,7 +50,7 @@ public class WebWeixinApi {
private static Pattern PATTERN_UUID_2 = Pattern.compile("window.QRLogin.code = (\\d+); window.QRLogin.uuid = \"(\\S+?)\";"); private static Pattern PATTERN_UUID_2 = Pattern.compile("window.QRLogin.code = (\\d+); window.QRLogin.uuid = \"(\\S+?)\";");
private static Pattern PATTERN_REDIRECT_URI_1 = Pattern.compile("window.code=(\\d+);"); private static Pattern PATTERN_REDIRECT_URI_1 = Pattern.compile("window.code=(\\d+);");
private static Pattern PATTERN_REDIRECT_URI_2 = Pattern.compile("window.code=(\\d+);\\s*window.redirect_uri=\"(\\S+?)\";"); private static Pattern PATTERN_REDIRECT_URI_2 = Pattern.compile("window.code=(\\d+);\\s*window.redirect_uri=\"(\\S+?)\";");
private static Pattern PATTERN_REDIRECT_URI_3 = Pattern.compile("http(s*)://wx(\\d*)\\.qq\\.com\\/"); private static Pattern PATTERN_REDIRECT_URI_3 = Pattern.compile("http(s*)://wx(\\d*)\\.qq\\.com/");
/** /**
* 上传媒体文件分片大小 * 上传媒体文件分片大小
@ -59,6 +59,9 @@ public class WebWeixinApi {
/** /**
* 获取微信uuid * 获取微信uuid
*
* @param httpClient http客户端
* @return 返回数据
*/ */
public JSONObject getWxUuid(HttpClient httpClient) { public JSONObject getWxUuid(HttpClient httpClient) {
try { try {
@ -113,7 +116,9 @@ public class WebWeixinApi {
/** /**
* 获取二维码 * 获取二维码
* *
* @param uuid * @param httpClient http客户端
* @param uuid uuid
* @return 二维码图片字节数据
*/ */
public byte[] getQR(HttpClient httpClient, public byte[] getQR(HttpClient httpClient,
String uuid) { String uuid) {
@ -147,7 +152,10 @@ public class WebWeixinApi {
/** /**
* 获取跳转uri等待扫码认证 * 获取跳转uri等待扫码认证
* *
* @return * @param httpClient http客户端
* @param tip 登录tip
* @param uuid uuid
* @return 返回数据
*/ */
public JSONObject getRedirectUri(HttpClient httpClient, public JSONObject getRedirectUri(HttpClient httpClient,
LoginTipEnum tip, LoginTipEnum tip,
@ -216,6 +224,10 @@ public class WebWeixinApi {
/** /**
* 获取登录认证码 * 获取登录认证码
* 此方法执行后其它web端微信pc端都会下线 * 此方法执行后其它web端微信pc端都会下线
*
* @param httpClient http客户端
* @param redirectUri 调整uri
* @return 返回数据
*/ */
public JSONObject getLoginCode(HttpClient httpClient, public JSONObject getLoginCode(HttpClient httpClient,
String redirectUri) { String redirectUri) {
@ -236,9 +248,7 @@ public class WebWeixinApi {
HttpEntity entity = response.getEntity(); HttpEntity entity = response.getEntity();
String res = EntityUtils.toString(entity, Consts.UTF_8); String res = EntityUtils.toString(entity, Consts.UTF_8);
JSONObject result = JSONObject.parseObject(XML.toJSONObject(res).toString()).getJSONObject("error"); return JSONObject.parseObject(XML.toJSONObject(res).toString()).getJSONObject("error");
return result;
} catch (Exception e) { } catch (Exception e) {
logger.error("获取登录认证码异常", e); logger.error("获取登录认证码异常", e);
return null; return null;
@ -247,21 +257,25 @@ public class WebWeixinApi {
/** /**
* 退出登录 * 退出登录
*
* @param httpClient http客户端
* @param urlVersion url版本号
* @param baseRequest BaseRequest
*/ */
public void logout(HttpClient httpClient, public void logout(HttpClient httpClient,
String urlVersion, String urlVersion,
BaseRequest BaseRequest) { BaseRequest baseRequest) {
try { try {
List<NameValuePair> pairList = new ArrayList<>(); List<NameValuePair> pairList = new ArrayList<>();
pairList.add(new BasicNameValuePair("sid", BaseRequest.getSid())); pairList.add(new BasicNameValuePair("sid", baseRequest.getSid()));
pairList.add(new BasicNameValuePair("uin", BaseRequest.getUin())); pairList.add(new BasicNameValuePair("uin", baseRequest.getUin()));
//分两步进行 //分两步进行
for (int i = 0; i <= 1; i++) { for (int i = 0; i <= 1; i++) {
String url = new ST(PropertiesUtil.getProperty("webwx-url.logout_url")) String url = new ST(PropertiesUtil.getProperty("webwx-url.logout_url"))
.add("urlVersion", urlVersion) .add("urlVersion", urlVersion)
.add("type", i) .add("type", i)
.add("skey", StringUtil.encodeURL(BaseRequest.getSkey(), Consts.UTF_8.name())) .add("skey", StringUtil.encodeURL(baseRequest.getSkey(), Consts.UTF_8.name()))
.render(); .render();
HttpPost httpPost = new HttpPost(url); HttpPost httpPost = new HttpPost(url);
@ -279,12 +293,16 @@ public class WebWeixinApi {
/** /**
* push登录 * push登录
*
* @param httpClient http客户端
* @param urlVersion url版本号
* @param wxuin uin
* @return 返回数据
*/ */
public JSONObject pushLogin(HttpClient httpClient, public JSONObject pushLogin(HttpClient httpClient,
String urlVersion, String urlVersion,
String wxuin) { String wxuin) {
try { try {
long millis = System.currentTimeMillis();
String url = new ST(PropertiesUtil.getProperty("webwx-url.pushlogin_url")) String url = new ST(PropertiesUtil.getProperty("webwx-url.pushlogin_url"))
.add("urlVersion", urlVersion) .add("urlVersion", urlVersion)
.add("uin", wxuin) .add("uin", wxuin)
@ -311,11 +329,17 @@ public class WebWeixinApi {
/** /**
* 获取初始化数据 * 获取初始化数据
*
* @param httpClient http客户端
* @param urlVersion url版本号
* @param passticket passticket
* @param baseRequest BaseRequest
* @return 返回数据
*/ */
public JSONObject webWeixinInit(HttpClient httpClient, public JSONObject webWeixinInit(HttpClient httpClient,
String urlVersion, String urlVersion,
String passticket, String passticket,
BaseRequest BaseRequest) { BaseRequest baseRequest) {
try { try {
String url = new ST(PropertiesUtil.getProperty("webwx-url.webwxinit_url")) String url = new ST(PropertiesUtil.getProperty("webwx-url.webwxinit_url"))
.add("urlVersion", urlVersion) .add("urlVersion", urlVersion)
@ -327,7 +351,7 @@ public class WebWeixinApi {
httpPost.setHeader("Content-type", ContentType.APPLICATION_JSON.toString()); httpPost.setHeader("Content-type", ContentType.APPLICATION_JSON.toString());
JSONObject paramJson = new JSONObject(); JSONObject paramJson = new JSONObject();
paramJson.put("BaseRequest", BaseRequest); paramJson.put("BaseRequest", baseRequest);
HttpEntity paramEntity = new StringEntity(paramJson.toJSONString(), Consts.UTF_8); HttpEntity paramEntity = new StringEntity(paramJson.toJSONString(), Consts.UTF_8);
httpPost.setEntity(paramEntity); httpPost.setEntity(paramEntity);
@ -350,12 +374,17 @@ public class WebWeixinApi {
/** /**
* 开启消息状态通知 * 开启消息状态通知
* *
* @return * @param httpClient http客户端
* @param urlVersion url版本号
* @param passticket passticket
* @param baseRequest BaseRequest
* @param loginUserName 当前登录账号用户名
* @return 返回数据
*/ */
public JSONObject statusNotify(HttpClient httpClient, public JSONObject statusNotify(HttpClient httpClient,
String urlVersion, String urlVersion,
String passticket, String passticket,
BaseRequest BaseRequest, BaseRequest baseRequest,
String loginUserName) { String loginUserName) {
try { try {
String url = new ST(PropertiesUtil.getProperty("webwx-url.statusnotify_url")) String url = new ST(PropertiesUtil.getProperty("webwx-url.statusnotify_url"))
@ -367,7 +396,7 @@ public class WebWeixinApi {
httpPost.setHeader("Content-type", ContentType.APPLICATION_JSON.toString()); httpPost.setHeader("Content-type", ContentType.APPLICATION_JSON.toString());
JSONObject paramJson = new JSONObject(); JSONObject paramJson = new JSONObject();
paramJson.put("BaseRequest", BaseRequest); paramJson.put("BaseRequest", baseRequest);
paramJson.put("ClientMsgId", System.currentTimeMillis()); paramJson.put("ClientMsgId", System.currentTimeMillis());
paramJson.put("Code", 3); paramJson.put("Code", 3);
paramJson.put("FromUserName", loginUserName); paramJson.put("FromUserName", loginUserName);
@ -393,21 +422,27 @@ public class WebWeixinApi {
/** /**
* 服务端状态同步心跳 * 服务端状态同步心跳
*
* @param httpClient http客户端
* @param urlVersion url版本号
* @param baseRequest BaseRequest
* @param syncKeyList SyncKeyList
* @return 返回数据
*/ */
public JSONObject syncCheck(HttpClient httpClient, public JSONObject syncCheck(HttpClient httpClient,
String urlVersion, String urlVersion,
BaseRequest BaseRequest, BaseRequest baseRequest,
JSONArray SyncKeyList) { JSONArray syncKeyList) {
try { try {
long millis = System.currentTimeMillis(); long millis = System.currentTimeMillis();
String url = new ST(PropertiesUtil.getProperty("webwx-url.synccheck_url")) String url = new ST(PropertiesUtil.getProperty("webwx-url.synccheck_url"))
.add("urlVersion", urlVersion) .add("urlVersion", urlVersion)
.add("r", millis) .add("r", millis)
.add("skey", StringUtil.encodeURL(BaseRequest.getSkey(), Consts.UTF_8.name())) .add("skey", StringUtil.encodeURL(baseRequest.getSkey(), Consts.UTF_8.name()))
.add("sid", BaseRequest.getSid()) .add("sid", baseRequest.getSid())
.add("uin", BaseRequest.getUin()) .add("uin", baseRequest.getUin())
.add("deviceid", WechatUtil.createDeviceID()) .add("deviceid", WechatUtil.createDeviceID())
.add("synckey", StringUtil.encodeURL(WechatUtil.syncKeyListToString(SyncKeyList), Consts.UTF_8.name())) .add("synckey", StringUtil.encodeURL(WechatUtil.syncKeyListToString(syncKeyList), Consts.UTF_8.name()))
.add("_", millis) .add("_", millis)
.render(); .render();
@ -446,6 +481,12 @@ public class WebWeixinApi {
/** /**
* 获取全部联系人列表 * 获取全部联系人列表
*
* @param httpClient http客户端
* @param urlVersion url版本号
* @param passticket passticket
* @param skey skey
* @return 返回数据
*/ */
public JSONObject getContact(HttpClient httpClient, public JSONObject getContact(HttpClient httpClient,
String urlVersion, String urlVersion,
@ -479,11 +520,18 @@ public class WebWeixinApi {
/** /**
* 批量获取指定用户信息 * 批量获取指定用户信息
*
* @param httpClient http客户端
* @param urlVersion url版本号
* @param passticket passticket
* @param baseRequest BaseRequest
* @param batchContactList 联系人列表
* @return 返回数据
*/ */
public JSONObject batchGetContact(HttpClient httpClient, public JSONObject batchGetContact(HttpClient httpClient,
String urlVersion, String urlVersion,
String passticket, String passticket,
BaseRequest BaseRequest, BaseRequest baseRequest,
JSONArray batchContactList) { JSONArray batchContactList) {
try { try {
String url = new ST(PropertiesUtil.getProperty("webwx-url.batchgetcontact_url")) String url = new ST(PropertiesUtil.getProperty("webwx-url.batchgetcontact_url"))
@ -496,7 +544,7 @@ public class WebWeixinApi {
httpPost.setHeader("Content-type", ContentType.APPLICATION_JSON.toString()); httpPost.setHeader("Content-type", ContentType.APPLICATION_JSON.toString());
JSONObject paramJson = new JSONObject(); JSONObject paramJson = new JSONObject();
paramJson.put("BaseRequest", BaseRequest); paramJson.put("BaseRequest", baseRequest);
paramJson.put("Count", batchContactList.size()); paramJson.put("Count", batchContactList.size());
paramJson.put("List", batchContactList); paramJson.put("List", batchContactList);
HttpEntity paramEntity = new StringEntity(paramJson.toJSONString(), Consts.UTF_8); HttpEntity paramEntity = new StringEntity(paramJson.toJSONString(), Consts.UTF_8);
@ -520,17 +568,24 @@ public class WebWeixinApi {
/** /**
* 从服务端同步新数据 * 从服务端同步新数据
*
* @param httpClient http客户端
* @param urlVersion url版本号
* @param passticket passticket
* @param baseRequest BaseRequest
* @param syncKey syncKey
* @return 返回数据
*/ */
public JSONObject webWxSync(HttpClient httpClient, public JSONObject webWxSync(HttpClient httpClient,
String urlVersion, String urlVersion,
String passticket, String passticket,
BaseRequest BaseRequest, BaseRequest baseRequest,
JSONObject SyncKey) { JSONObject syncKey) {
try { try {
String url = new ST(PropertiesUtil.getProperty("webwx-url.webwxsync_url")) String url = new ST(PropertiesUtil.getProperty("webwx-url.webwxsync_url"))
.add("urlVersion", urlVersion) .add("urlVersion", urlVersion)
.add("skey", BaseRequest.getSkey()) .add("skey", baseRequest.getSkey())
.add("sid", BaseRequest.getSid()) .add("sid", baseRequest.getSid())
.add("pass_ticket", StringUtil.encodeURL(passticket, Consts.UTF_8.name())) .add("pass_ticket", StringUtil.encodeURL(passticket, Consts.UTF_8.name()))
.render(); .render();
@ -538,8 +593,8 @@ public class WebWeixinApi {
httpPost.setHeader("Content-type", ContentType.APPLICATION_JSON.toString()); httpPost.setHeader("Content-type", ContentType.APPLICATION_JSON.toString());
JSONObject paramJson = new JSONObject(); JSONObject paramJson = new JSONObject();
paramJson.put("BaseRequest", BaseRequest); paramJson.put("BaseRequest", baseRequest);
paramJson.put("SyncKey", SyncKey); paramJson.put("SyncKey", syncKey);
HttpEntity paramEntity = new StringEntity(paramJson.toJSONString(), Consts.UTF_8); HttpEntity paramEntity = new StringEntity(paramJson.toJSONString(), Consts.UTF_8);
httpPost.setEntity(paramEntity); httpPost.setEntity(paramEntity);
@ -561,6 +616,13 @@ public class WebWeixinApi {
/** /**
* 发送消息 * 发送消息
*
* @param httpClient http客户端
* @param urlVersion url版本号
* @param passticket passticket
* @param baseRequest BaseRequest
* @param message 消息
* @return 返回数据
*/ */
public JSONObject sendMsg(HttpClient httpClient, public JSONObject sendMsg(HttpClient httpClient,
String urlVersion, String urlVersion,
@ -592,9 +654,7 @@ public class WebWeixinApi {
HttpEntity entity = response.getEntity(); HttpEntity entity = response.getEntity();
String res = EntityUtils.toString(entity, Consts.UTF_8); String res = EntityUtils.toString(entity, Consts.UTF_8);
JSONObject result = JSONObject.parseObject(res); return JSONObject.parseObject(res);
return result;
} catch (Exception e) { } catch (Exception e) {
logger.error("发送消息异常", e); logger.error("发送消息异常", e);
return null; return null;
@ -604,17 +664,17 @@ public class WebWeixinApi {
/** /**
* 上传媒体文件(支持大文件自动分片上传) * 上传媒体文件(支持大文件自动分片上传)
* *
* @param httpClient * @param httpClient http客户端
* @param urlVersion * @param urlVersion url版本号
* @param passticket * @param passticket passticket
* @param baseRequest * @param baseRequest BaseRequest
* @param fromUserName * @param fromUserName 发送者用户名
* @param toUserName * @param toUserName 接受者用户名
* @param dataTicket * @param dataTicket dataTicket
* @param mediaData * @param mediaData 媒体文件二进制数据
* @param mediaName * @param mediaName 媒体文件名称
* @param contentType * @param contentType 媒体文件类型
* @return * @return 返回数据
*/ */
public JSONObject uploadMedia(HttpClient httpClient, public JSONObject uploadMedia(HttpClient httpClient,
String urlVersion, String urlVersion,
@ -691,12 +751,12 @@ public class WebWeixinApi {
break; break;
} }
JSONObject BaseResponse = result.getJSONObject("BaseResponse"); JSONObject baseResponse = result.getJSONObject("BaseResponse");
if (BaseResponse == null) { if (baseResponse == null) {
break; break;
} }
int Ret = BaseResponse.getIntValue("Ret"); int ret = baseResponse.getIntValue("Ret");
if (Ret != 0) { if (ret != 0) {
break; break;
} }
} }
@ -710,6 +770,13 @@ public class WebWeixinApi {
/** /**
* 发送图片消息 * 发送图片消息
*
* @param httpClient http客户端
* @param urlVersion url版本号
* @param passticket passticket
* @param baseRequest BaseRequest
* @param message 消息
* @return 返回数据
*/ */
public JSONObject sendImageMsg(HttpClient httpClient, public JSONObject sendImageMsg(HttpClient httpClient,
String urlVersion, String urlVersion,
@ -741,9 +808,7 @@ public class WebWeixinApi {
HttpEntity entity = response.getEntity(); HttpEntity entity = response.getEntity();
String res = EntityUtils.toString(entity, Consts.UTF_8); String res = EntityUtils.toString(entity, Consts.UTF_8);
JSONObject result = JSONObject.parseObject(res); return JSONObject.parseObject(res);
return result;
} catch (Exception e) { } catch (Exception e) {
logger.error("发送图片消息异常", e); logger.error("发送图片消息异常", e);
return null; return null;

View File

@ -2,11 +2,13 @@ package com.hotlcc.wechat4j.enums;
/** /**
* 微信退出类型 * 微信退出类型
*
* @author Allen
*/ */
public enum ExitTypeEnum { public enum ExitTypeEnum {
ERROR_EXIT("错误导致退出"), ERROR_EXIT("错误退出"),
LOCAL_EXIT("次手动退出"), LOCAL_EXIT("退出"),
REMOTE_EXIT("远程操作退出"); REMOTE_EXIT("远程退出");
private String desc; private String desc;

View File

@ -3,8 +3,9 @@ package com.hotlcc.wechat4j.enums;
/** /**
* 等待确认登录的tip * 等待确认登录的tip
* *
* @author https://gitee.com/hotlcc * @author Allen
*/ */
@SuppressWarnings("unused")
public enum LoginTipEnum { public enum LoginTipEnum {
TIP_0(0, "扫码登录"), TIP_0(0, "扫码登录"),
TIP_1(1, "确认登录"); TIP_1(1, "确认登录");

View File

@ -3,8 +3,9 @@ package com.hotlcc.wechat4j.enums;
/** /**
* 消息类型enum * 消息类型enum
* *
* @author https://gitee.com/hotlcc * @author Allen
*/ */
@SuppressWarnings({"unused"})
public enum MsgTypeEnum { public enum MsgTypeEnum {
TEXT_MSG(1, "文本消息"), TEXT_MSG(1, "文本消息"),
IMAGE_MSG(3, "图片消息"), IMAGE_MSG(3, "图片消息"),

View File

@ -3,7 +3,7 @@ package com.hotlcc.wechat4j.enums;
/** /**
* 操作系统enum * 操作系统enum
* *
* @author https://gitee.com/hotlcc * @author Allen
*/ */
public enum OperatingSystemEnum { public enum OperatingSystemEnum {
DARWIN("darwin"), DARWIN("darwin"),

View File

@ -1,5 +1,10 @@
package com.hotlcc.wechat4j.enums; package com.hotlcc.wechat4j.enums;
/**
* Ret代码
*
* @author Allen
*/
public enum RetcodeEnum { public enum RetcodeEnum {
RECODE_0(0, "正常"), RECODE_0(0, "正常"),
RECODE_1100(1100, "失败/登出微信"), RECODE_1100(1100, "失败/登出微信"),

View File

@ -1,5 +1,10 @@
package com.hotlcc.wechat4j.enums; package com.hotlcc.wechat4j.enums;
/**
* Selector代码
*
* @author Allen
*/
public enum SelectorEnum { public enum SelectorEnum {
SELECTOR_0(0, "正常"), SELECTOR_0(0, "正常"),
SELECTOR_2(2, "有新消息"), SELECTOR_2(2, "有新消息"),
@ -15,10 +20,6 @@ public enum SelectorEnum {
this.desc = desc; this.desc = desc;
} }
public int getCode() {
return code;
}
public static SelectorEnum valueOf(int code) { public static SelectorEnum valueOf(int code) {
SelectorEnum[] es = values(); SelectorEnum[] es = values();
for (SelectorEnum e : es) { for (SelectorEnum e : es) {

View File

@ -5,35 +5,37 @@ import com.hotlcc.wechat4j.enums.ExitTypeEnum;
/** /**
* 退出事件处理器 * 退出事件处理器
*
* @author Allen
*/ */
public interface ExitEventHandler { public interface ExitEventHandler {
/** /**
* 针对所有类型的退出事件 * 针对所有类型的退出事件
* *
* @param wechat * @param wechat 微信客户端
* @param type * @param type 退出类型
* @param t * @param t 异常
*/ */
void handleAllType(Wechat wechat, ExitTypeEnum type, Throwable t); void handleAllType(Wechat wechat, ExitTypeEnum type, Throwable t);
/** /**
* 针对错误导致的退出事件 * 针对错误导致的退出事件
* *
* @param wechat * @param wechat 微信客户端
*/ */
void handleErrorExitEvent(Wechat wechat); void handleErrorExitEvent(Wechat wechat);
/** /**
* 针对远程人为导致的退出事件 * 针对远程人为导致的退出事件
* *
* @param wechat * @param wechat 微信客户端
*/ */
void handleRemoteExitEvent(Wechat wechat); void handleRemoteExitEvent(Wechat wechat);
/** /**
* 针对本地任务导致的退出事件 * 针对本地任务导致的退出事件
* *
* @param wechat * @param wechat 微信客户端
*/ */
void handleLocalExitEvent(Wechat wechat); void handleLocalExitEvent(Wechat wechat);
} }

View File

@ -4,14 +4,16 @@ import com.hotlcc.wechat4j.Wechat;
import com.hotlcc.wechat4j.model.ReceivedMsg; import com.hotlcc.wechat4j.model.ReceivedMsg;
/** /**
* 接收消息处理器 * 接收消息的消息处理器
*
* @author Allen
*/ */
public interface ReceivedMsgHandler { public interface ReceivedMsgHandler {
/** /**
* 处理所有类型的消息 * 处理所有类型的消息
* *
* @param wechat * @param wechat 微信客户端
* @param msg * @param msg 接收的消息
*/ */
void handleAllType(Wechat wechat, ReceivedMsg msg); void handleAllType(Wechat wechat, ReceivedMsg msg);
} }

View File

@ -1,15 +1,23 @@
package com.hotlcc.wechat4j.model; package com.hotlcc.wechat4j.model;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.annotation.JSONField;
import lombok.Getter; import lombok.Getter;
import lombok.Setter;
import java.io.Serializable; import java.io.Serializable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
/**
* AppInfo
*
* @author Allen
*/
@Getter @Getter
@Setter
public final class AppInfo implements Serializable { public final class AppInfo implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
@ -25,10 +33,7 @@ public final class AppInfo implements Serializable {
if (info == null) { if (info == null) {
return null; return null;
} }
AppInfo appInfo = new AppInfo(); return JSON.toJavaObject(info, AppInfo.class);
appInfo.type = info.getInteger("Type");
appInfo.appID = info.getString("AppID");
return appInfo;
} }
public static List<AppInfo> valueOf(JSONArray infos) { public static List<AppInfo> valueOf(JSONArray infos) {

View File

@ -9,6 +9,8 @@ import java.io.Serializable;
/** /**
* 基本请求模型 * 基本请求模型
*
* @author Allen
*/ */
@Getter @Getter
@Setter @Setter

View File

@ -6,6 +6,8 @@ import lombok.Setter;
/** /**
* 媒体消息 * 媒体消息
*
* @author Allen
*/ */
@Getter @Getter
@Setter @Setter

View File

@ -1,15 +1,18 @@
package com.hotlcc.wechat4j.model; package com.hotlcc.wechat4j.model;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.annotation.JSONField;
import lombok.Getter; import lombok.Getter;
import lombok.Setter;
import java.io.Serializable; import java.io.Serializable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@Getter @Getter
@Setter
public final class ReceivedMsg implements Serializable { public final class ReceivedMsg implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
@ -78,37 +81,7 @@ public final class ReceivedMsg implements Serializable {
return null; return null;
} }
ReceivedMsg receivedMsg = new ReceivedMsg(); return JSON.toJavaObject(msg, ReceivedMsg.class);
receivedMsg.subMsgType = msg.getInteger("SubMsgType");
receivedMsg.voiceLength = msg.getLong("VoiceLength");
receivedMsg.fileName = msg.getString("FileName");
receivedMsg.imgHeight = msg.getLong("ImgHeight");
receivedMsg.toUserName = msg.getString("ToUserName");
receivedMsg.hasProductId = msg.getLong("HasProductId");
receivedMsg.imgStatus = msg.getInteger("ImgStatus");
receivedMsg.url = msg.getString("Url");
receivedMsg.imgWidth = msg.getInteger("ImgWidth");
receivedMsg.forwardFlag = msg.getInteger("ForwardFlag");
receivedMsg.status = msg.getInteger("Status");
receivedMsg.ticket = msg.getString("Ticket");
receivedMsg.recommendInfo = com.hotlcc.wechat4j.model.RecommendInfo.valueOf(msg.getJSONObject("RecommendInfo"));
receivedMsg.createTime = msg.getLong("CreateTime");
receivedMsg.newMsgId = msg.getLong("NewMsgId");
receivedMsg.msgType = msg.getInteger("MsgType");
receivedMsg.encryFileName = msg.getString("EncryFileName");
receivedMsg.msgId = msg.getString("MsgId");
receivedMsg.statusNotifyCode = msg.getInteger("StatusNotifyCode");
receivedMsg.appInfo = com.hotlcc.wechat4j.model.AppInfo.valueOf(msg.getJSONObject("AppInfo"));
receivedMsg.playLength = msg.getLong("PlayLength");
receivedMsg.mediaId = msg.getString("MediaId");
receivedMsg.content = msg.getString("Content");
receivedMsg.statusNotifyUserName = msg.getString("StatusNotifyUserName");
receivedMsg.fromUserName = msg.getString("FromUserName");
receivedMsg.oriContent = msg.getString("OriContent");
receivedMsg.fileSize = msg.getString("FileSize");
return receivedMsg;
} }
public static List<ReceivedMsg> valueOf(JSONArray msgs) { public static List<ReceivedMsg> valueOf(JSONArray msgs) {

View File

@ -1,15 +1,23 @@
package com.hotlcc.wechat4j.model; package com.hotlcc.wechat4j.model;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.annotation.JSONField;
import lombok.Getter; import lombok.Getter;
import lombok.Setter;
import java.io.Serializable; import java.io.Serializable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
/**
* RecommendInfo
*
* @author Allen
*/
@Getter @Getter
@Setter
public final class RecommendInfo implements Serializable { public final class RecommendInfo implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
@ -50,24 +58,7 @@ public final class RecommendInfo implements Serializable {
return null; return null;
} }
RecommendInfo recommendInfo = new RecommendInfo(); return JSON.toJavaObject(info, RecommendInfo.class);
recommendInfo.ticket = info.getString("Ticket");
recommendInfo.userName = info.getString("UserName");
recommendInfo.sex = info.getInteger("Sex");
recommendInfo.attrStatus = info.getInteger("AttrStatus");
recommendInfo.city = info.getString("City");
recommendInfo.nickName = info.getString("NickName");
recommendInfo.scene = info.getInteger("Scene");
recommendInfo.province = info.getString("Province");
recommendInfo.content = info.getString("Content");
recommendInfo.alias = info.getString("Alias");
recommendInfo.signature = info.getString("Signature");
recommendInfo.opCode = info.getInteger("OpCode");
recommendInfo.qqNum = info.getLong("QQNum");
recommendInfo.verifyFlag = info.getInteger("VerifyFlag");
return recommendInfo;
} }
public static List<RecommendInfo> valueOf(JSONArray infos) { public static List<RecommendInfo> valueOf(JSONArray infos) {

View File

@ -1,9 +1,11 @@
package com.hotlcc.wechat4j.model; package com.hotlcc.wechat4j.model;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.annotation.JSONField;
import lombok.Getter; import lombok.Getter;
import lombok.Setter;
import java.io.Serializable; import java.io.Serializable;
import java.util.ArrayList; import java.util.ArrayList;
@ -11,8 +13,11 @@ import java.util.List;
/** /**
* 微信用户信息 * 微信用户信息
*
* @author Allen
*/ */
@Getter @Getter
@Setter
public final class UserInfo implements Serializable { public final class UserInfo implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
@ -87,41 +92,7 @@ public final class UserInfo implements Serializable {
return null; return null;
} }
UserInfo userInfo = new UserInfo(); return JSON.toJavaObject(info, UserInfo.class);
userInfo.uin = info.getLong("Uin");
userInfo.nickName = info.getString("NickName");
userInfo.headImgUrl = info.getString("HeadImgUrl");
userInfo.contactFlag = info.getInteger("ContactFlag");
userInfo.memberCount = info.getInteger("MemberCount");
userInfo.memberList = valueOf(info.getJSONArray("MemberList"));
userInfo.remarkName = info.getString("RemarkName");
userInfo.hideInputBarFlag = info.getInteger("HideInputBarFlag");
userInfo.sex = info.getInteger("Sex");
userInfo.signature = info.getString("Signature");
userInfo.verifyFlag = info.getInteger("VerifyFlag");
userInfo.ownerUin = info.getLong("OwnerUin");
userInfo.pyInitial = info.getString("PYInitial");
userInfo.pyQuanPin = info.getString("PYQuanPin");
userInfo.remarkPYInitial = info.getString("RemarkPYInitial");
userInfo.remarkPYQuanPin = info.getString("RemarkPYQuanPin");
userInfo.starFriend = info.getInteger("StarFriend");
userInfo.appAccountFlag = info.getInteger("AppAccountFlag");
userInfo.statues = info.getInteger("Statues");
userInfo.attrStatus = info.getInteger("AttrStatus");
userInfo.province = info.getString("Province");
userInfo.city = info.getString("City");
userInfo.alias = info.getString("Alias");
userInfo.snsFlag = info.getInteger("SnsFlag");
userInfo.uniFriend = info.getInteger("UniFriend");
userInfo.displayName = info.getString("DisplayName");
userInfo.chatRoomId = info.getLong("ChatRoomId");
userInfo.keyWord = info.getString("KeyWord");
userInfo.encryChatRoomId = info.getString("EncryChatRoomId");
userInfo.isOwner = info.getInteger("IsOwner");
userInfo.userName = info.getString("UserName");
return userInfo;
} }
public static List<UserInfo> valueOf(JSONArray infos) { public static List<UserInfo> valueOf(JSONArray infos) {

View File

@ -8,6 +8,8 @@ import java.io.Serializable;
/** /**
* 要发送的消息 * 要发送的消息
*
* @author Allen
*/ */
@Getter @Getter
@Setter @Setter

View File

@ -3,12 +3,23 @@ package com.hotlcc.wechat4j.util;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/**
* 通用工具类
*
* @author Allen
*/
public final class CommonUtil { public final class CommonUtil {
private static Logger logger = LoggerFactory.getLogger(CommonUtil.class); private static Logger logger = LoggerFactory.getLogger(CommonUtil.class);
private CommonUtil() { private CommonUtil() {
} }
/**
* 睡眠线程
*
* @param millis 时间
* @param nanos nanos
*/
public static void threadSleep(long millis, int nanos) { public static void threadSleep(long millis, int nanos) {
try { try {
Thread.sleep(millis, nanos); Thread.sleep(millis, nanos);
@ -17,6 +28,11 @@ public final class CommonUtil {
} }
} }
/**
* 睡眠线程
*
* @param millis 时间
*/
public static void threadSleep(long millis) { public static void threadSleep(long millis) {
try { try {
Thread.sleep(millis); Thread.sleep(millis);

View File

@ -12,6 +12,8 @@ import java.io.IOException;
/** /**
* 文件工具类 * 文件工具类
*
* @author Allen
*/ */
public final class FileUtil { public final class FileUtil {
private static Logger logger = LoggerFactory.getLogger(FileUtil.class); private static Logger logger = LoggerFactory.getLogger(FileUtil.class);
@ -19,6 +21,12 @@ public final class FileUtil {
private FileUtil() { private FileUtil() {
} }
/**
* 从文件中获取二进制数据
*
* @param file 文件
* @return 二进制数据
*/
public static byte[] getBytes(File file) { public static byte[] getBytes(File file) {
if (file == null) { if (file == null) {
throw new IllegalArgumentException("参数file不能为null"); throw new IllegalArgumentException("参数file不能为null");
@ -62,6 +70,12 @@ public final class FileUtil {
} }
} }
/**
* 获取文件的ContentType
*
* @param file 文件
* @return ContentType
*/
public static ContentType getContentBody(File file) { public static ContentType getContentBody(File file) {
String mimeType = new MimetypesFileTypeMap().getContentType(file); String mimeType = new MimetypesFileTypeMap().getContentType(file);
ContentType contentType = ContentType.parse(mimeType); ContentType contentType = ContentType.parse(mimeType);

View File

@ -7,6 +7,11 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.util.Properties; import java.util.Properties;
/**
* Properties工具类
*
* @author Allen
*/
public final class PropertiesUtil { public final class PropertiesUtil {
private static Logger logger = LoggerFactory.getLogger(PropertiesUtil.class); private static Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);

View File

@ -16,15 +16,13 @@ import java.io.ByteArrayInputStream;
import java.io.File; import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/** /**
* 二维码工具类 * 二维码工具类
* *
* @author Allen * @author Allen
*/ */
@SuppressWarnings({"unused", "WeakerAccess"})
public final class QRCodeUtil { public final class QRCodeUtil {
private static Logger logger = LoggerFactory.getLogger(QRCodeUtil.class); private static Logger logger = LoggerFactory.getLogger(QRCodeUtil.class);
@ -34,7 +32,7 @@ public final class QRCodeUtil {
/** /**
* 从BitMatrix中得到boolean矩阵不去除周围空白部分 * 从BitMatrix中得到boolean矩阵不去除周围空白部分
* *
* @return * @return 得到的boolean矩阵
*/ */
private static boolean[][] toBoolMatrix(BitMatrix matrix) { private static boolean[][] toBoolMatrix(BitMatrix matrix) {
return toBoolMatrix(matrix, false); return toBoolMatrix(matrix, false);
@ -43,9 +41,9 @@ public final class QRCodeUtil {
/** /**
* 从BitMatrix中得到boolean矩阵 * 从BitMatrix中得到boolean矩阵
* *
* @param matrix * @param matrix BitMatrix
* @param noMargin 是否去除周围空白 * @param noMargin 是否去除周围空白
* @return * @return 得到的boolean矩阵
*/ */
private static boolean[][] toBoolMatrix(BitMatrix matrix, boolean noMargin) { private static boolean[][] toBoolMatrix(BitMatrix matrix, boolean noMargin) {
int width = matrix.getWidth(); int width = matrix.getWidth();
@ -60,8 +58,8 @@ public final class QRCodeUtil {
right = width - br[1] - 1; right = width - br[1] - 1;
} }
boolean[][] m = new boolean[height - top - bottom][width - left - right]; boolean[][] m = new boolean[height - top - bottom][width - left - right];
for (int h = 0 + top, i = 0; h < height - bottom; h++, i++) { for (int h = top, i = 0; h < height - bottom; h++, i++) {
for (int w = 0 + left, j = 0; w < width - right; w++, j++) { for (int w = left, j = 0; w < width - right; w++, j++) {
m[i][j] = matrix.get(w, h); m[i][j] = matrix.get(w, h);
} }
} }
@ -71,8 +69,8 @@ public final class QRCodeUtil {
/** /**
* 将矩阵逆时针转90度 * 将矩阵逆时针转90度
* *
* @param matrix * @param matrix 旋转前的矩阵
* @return * @return 旋转后的矩阵
*/ */
private static boolean[][] reverseMatrix(boolean[][] matrix) { private static boolean[][] reverseMatrix(boolean[][] matrix) {
if (matrix == null) { if (matrix == null) {
@ -95,15 +93,14 @@ public final class QRCodeUtil {
/** /**
* 从boolMatrix左上角判断二维码定位标记的大小 * 从boolMatrix左上角判断二维码定位标记的大小
* *
* @param boolMatrix * @param boolMatrix bool矩阵
* @return * @return 定位标记大小
*/ */
private static int getBitCharSize(boolean[][] boolMatrix) { private static int getBitCharSize(boolean[][] boolMatrix) {
int a = 0, b = 0; int a = 0, b = 0;
out: out:
for (int i = 0, len = boolMatrix.length; i < len; i++) { for (boolean[] boolArr : boolMatrix) {
boolean find = false; boolean find = false;
boolean[] boolArr = boolMatrix[i];
for (int i2 = 0, len2 = boolArr.length; i2 < len2; i2++) { for (int i2 = 0, len2 = boolArr.length; i2 < len2; i2++) {
if (!find && boolArr[i2]) { if (!find && boolArr[i2]) {
find = true; find = true;
@ -122,59 +119,62 @@ public final class QRCodeUtil {
/** /**
* 从boolMatrix判断bit-char占位比 * 从boolMatrix判断bit-char占位比
* *
* @param boolMatrix * @param boolMatrix bool矩阵
* @return * @return 占位比
*/ */
private static int getBitCharRatio(boolean[][] boolMatrix) { private static int getBitCharRatio(boolean[][] boolMatrix) {
int[] size = new int[4]; int len = 4;
// 找出四个角的占位数
int[] size = new int[len];
size[0] = getBitCharSize(boolMatrix); size[0] = getBitCharSize(boolMatrix);
for (int i = 1; i < 4; i++) { for (int i = 1; i < len; i++) {
boolMatrix = reverseMatrix(boolMatrix); boolMatrix = reverseMatrix(boolMatrix);
size[i] = getBitCharSize(boolMatrix); size[i] = getBitCharSize(boolMatrix);
} }
// 统计每个占位数出现的次数
Map<Integer, Integer> map = new HashMap<>(); int[] num = new int[len];
for (int s : size) { for (int i = 0; i < len; i++) {
Integer count = map.get(s); int n = 0;
if (count == null) { for (int s : size) {
map.put(s, 1); if (s == size[i]) {
} else { n++;
map.put(s, count + 1); }
} }
num[i] = n;
} }
Set<Map.Entry<Integer, Integer>> entrySet = map.entrySet(); // 找出最多的次数
Integer k = null, v = null; int maxNum = num[0];
int flag = 0; for (int i = 1; i < len; i++) {
for (Map.Entry<Integer, Integer> entry : entrySet) { maxNum = Math.max(maxNum, num[i]);
if (flag++ == 0) { }
k = entry.getKey(); // 找出出现次数最多的占位数
v = entry.getValue(); int s = 0;
continue; for (int i = 0; i < len; i++) {
} if (num[i] == maxNum) {
if (entry.getValue() > v) { s = size[i];
k = entry.getKey();
v = entry.getValue();
} }
} }
return k.intValue() / 7; return s / 7;
} }
/** /**
* 将二维码图片转为字符矩阵 * 将二维码图片转为字符矩阵
* *
* @param image * @param image 二维码图片
* @return * @param onStr 实体字符串
* @param offStr 空白字符串
* @return 字符矩阵
*/ */
public static String toCharMatrix(BufferedImage image, String onStr, String offStr) { public static String toCharMatrix(BufferedImage image, String onStr, String offStr) {
LuminanceSource source = new BufferedImageLuminanceSource(image); LuminanceSource source = new BufferedImageLuminanceSource(image);
Binarizer binarizer = new HybridBinarizer(source); Binarizer binarizer = new HybridBinarizer(source);
BitMatrix matrix = null; BitMatrix matrix;
try { try {
matrix = binarizer.getBlackMatrix(); matrix = binarizer.getBlackMatrix();
boolean[][] boolMatrix = toBoolMatrix(matrix, true); boolean[][] boolMatrix = toBoolMatrix(matrix, true);
int ratio = getBitCharRatio(boolMatrix); int ratio = getBitCharRatio(boolMatrix);
StringBuffer sb = new StringBuffer(); StringBuilder sb = new StringBuilder();
for (int i = 0, len = boolMatrix.length; i < len; i += ratio) { for (int i = 0, len = boolMatrix.length; i < len; i += ratio) {
boolean[] boolArr = boolMatrix[i]; boolean[] boolArr = boolMatrix[i];
for (int i2 = 0, len2 = boolArr.length; i2 < len2; i2 += ratio) { for (int i2 = 0, len2 = boolArr.length; i2 < len2; i2 += ratio) {
@ -192,8 +192,8 @@ public final class QRCodeUtil {
/** /**
* 将二维码图片转为字符矩阵 * 将二维码图片转为字符矩阵
* *
* @param image * @param image 二维码图片
* @return * @return 字符矩阵
*/ */
public static String toCharMatrix(BufferedImage image) { public static String toCharMatrix(BufferedImage image) {
return toCharMatrix(image, " ", "██"); return toCharMatrix(image, " ", "██");
@ -202,8 +202,10 @@ public final class QRCodeUtil {
/** /**
* 将二维码图片转为字符矩阵 * 将二维码图片转为字符矩阵
* *
* @param data * @param data 二维码图片的字节数据
* @return * @param onStr 实体字符串
* @param offStr 空白字符串
* @return 字符矩阵
*/ */
public static String toCharMatrix(byte[] data, String onStr, String offStr) { public static String toCharMatrix(byte[] data, String onStr, String offStr) {
ByteArrayInputStream bais = null; ByteArrayInputStream bais = null;
@ -228,8 +230,8 @@ public final class QRCodeUtil {
/** /**
* 将二维码图片转为字符矩阵 * 将二维码图片转为字符矩阵
* *
* @param data * @param data 二维码图片的字节数据
* @return * @return 字符矩阵
*/ */
public static String toCharMatrix(byte[] data) { public static String toCharMatrix(byte[] data) {
return toCharMatrix(data, " ", "██"); return toCharMatrix(data, " ", "██");
@ -238,8 +240,8 @@ public final class QRCodeUtil {
/** /**
* 将二维码图片数据写入到临时文件 * 将二维码图片数据写入到临时文件
* *
* @param data * @param data 二维码图片的字节数据
* @return * @return 字符矩阵
*/ */
public static File writeToTempFile(byte[] data) { public static File writeToTempFile(byte[] data) {
FileOutputStream fos = null; FileOutputStream fos = null;
@ -266,12 +268,12 @@ public final class QRCodeUtil {
/** /**
* 打开二维码图片 * 打开二维码图片
* *
* @param data * @param data 二维码图片的字节数据
*/ */
public static void openQRCodeImage(byte[] data) { public static void openQRCodeImage(byte[] data) {
OperatingSystemEnum os = OperatingSystemEnum.currentOperatingSystem(); OperatingSystemEnum os = OperatingSystemEnum.currentOperatingSystem();
Runtime runtime = null; Runtime runtime;
File tmp = null; File tmp;
switch (os) { switch (os) {
case WINDOWS: case WINDOWS:
runtime = Runtime.getRuntime(); runtime = Runtime.getRuntime();

View File

@ -5,6 +5,11 @@ import java.net.URLDecoder;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.util.UUID; import java.util.UUID;
/**
* 字符串工具类
*
* @author Allen
*/
public final class StringUtil { public final class StringUtil {
private StringUtil() { private StringUtil() {
} }

View File

@ -4,6 +4,11 @@ import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.RandomStringUtils;
/**
* 微信工具类
*
* @author Allen
*/
public final class WechatUtil { public final class WechatUtil {
private WechatUtil() { private WechatUtil() {
} }
@ -14,7 +19,7 @@ public final class WechatUtil {
/** /**
* 创建一个设备ID * 创建一个设备ID
* *
* @return * @return 设备ID
*/ */
public static String createDeviceID() { public static String createDeviceID() {
return "e" + RandomStringUtils.random(15, STRING_CHARS_1); return "e" + RandomStringUtils.random(15, STRING_CHARS_1);
@ -23,7 +28,7 @@ public final class WechatUtil {
/** /**
* 创建一个消息ID * 创建一个消息ID
* *
* @return * @return 消息ID
*/ */
public static String createMsgId() { public static String createMsgId() {
return System.currentTimeMillis() + RandomStringUtils.random(4, STRING_CHARS_2); return System.currentTimeMillis() + RandomStringUtils.random(4, STRING_CHARS_2);
@ -32,8 +37,8 @@ public final class WechatUtil {
/** /**
* 把SyncKeyList转为字符串格式 * 把SyncKeyList转为字符串格式
* *
* @param SyncKeyList * @param SyncKeyList SyncKeyList
* @return * @return 字符串
*/ */
public static String syncKeyListToString(JSONArray SyncKeyList) { public static String syncKeyListToString(JSONArray SyncKeyList) {
if (SyncKeyList == null) { if (SyncKeyList == null) {
@ -55,8 +60,8 @@ public final class WechatUtil {
/** /**
* 根据ContentType得到微信上传所需的mediatype * 根据ContentType得到微信上传所需的mediatype
* *
* @param contentType * @param contentType contentType
* @return * @return 微信上传所需的mediatype
*/ */
public static String getMediatype(String contentType) { public static String getMediatype(String contentType) {
if (contentType == null) { if (contentType == null) {