From 7ec5dbfce3c4501517e2f1c564565e145026f86e Mon Sep 17 00:00:00 2001 From: hotlcc Date: Wed, 25 Jul 2018 16:13:07 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8F=90=E4=BA=A4=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/hotlcc/wechat4j/Wechat.java | 41 ++++++++++- .../com/hotlcc/wechat4j/api/WebWeixinApi.java | 72 ++++++++++++++++++- src/test/java/TestClass2.java | 35 ++++----- 3 files changed, 124 insertions(+), 24 deletions(-) diff --git a/src/main/java/com/hotlcc/wechat4j/Wechat.java b/src/main/java/com/hotlcc/wechat4j/Wechat.java index 4a1ff4a..7db535b 100644 --- a/src/main/java/com/hotlcc/wechat4j/Wechat.java +++ b/src/main/java/com/hotlcc/wechat4j/Wechat.java @@ -18,6 +18,7 @@ import org.apache.http.HttpResponse; import org.apache.http.client.CookieStore; import org.apache.http.client.HttpClient; import org.apache.http.conn.ConnectionKeepAliveStrategy; +import org.apache.http.cookie.Cookie; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy; import org.apache.http.impl.client.HttpClients; @@ -25,6 +26,7 @@ import org.apache.http.protocol.HttpContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; @@ -84,6 +86,27 @@ public class Wechat { this.webWeixinApi = webWeixinApi; } + private Cookie getCookie(String name) { + List cookies = cookieStore.getCookies(); + if (cookies == null) { + return null; + } + for (Cookie cookie : cookies) { + if (cookie.getName().equals(name)) { + return cookie; + } + } + return null; + } + + public String getCookieValue(String name) { + Cookie cookie = getCookie(name); + if (cookie == null) { + return null; + } + return cookie.getValue(); + } + public void addExitEventHandler(ExitEventHandler handler) { if (handler == null) { return; @@ -1049,7 +1072,7 @@ public class Wechat { * * @return */ - public JSONObject sendText(String content, String toUserName) { + public JSONObject sendText(String content, String userName) { BaseRequest baseRequest = new BaseRequest(wxsid, skey, wxuin); String msgId = WechatUtil.createMsgId(); @@ -1059,10 +1082,10 @@ public class Wechat { message.setContent(content); message.setFromUserName(loginUserName); message.setLocalID(msgId); - if (StringUtil.isEmpty(toUserName)) { + if (StringUtil.isEmpty(userName)) { message.setToUserName(loginUserName); } else { - message.setToUserName(toUserName); + message.setToUserName(userName); } message.setType(MsgTypeEnum.TEXT_MSG.getCode()); @@ -1120,4 +1143,16 @@ public class Wechat { return sendText(content, userName); } + + //TODO 待完成 + @Deprecated + public JSONObject sendImage(File image, String userName) { + 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 = webWeixinApi.uploadMedia(httpClient, passTicket, baseRequest, loginUserName, toUserName, dataTicket, image); + return result; + } } diff --git a/src/main/java/com/hotlcc/wechat4j/api/WebWeixinApi.java b/src/main/java/com/hotlcc/wechat4j/api/WebWeixinApi.java index 27eb28c..7b2390c 100644 --- a/src/main/java/com/hotlcc/wechat4j/api/WebWeixinApi.java +++ b/src/main/java/com/hotlcc/wechat4j/api/WebWeixinApi.java @@ -26,6 +26,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.stringtemplate.v4.ST; +import javax.activation.MimetypesFileTypeMap; +import java.io.File; +import java.io.FileInputStream; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; @@ -542,7 +545,6 @@ public class WebWeixinApi { paramJson.put("BaseRequest", baseRequest); paramJson.put("Msg", message); paramJson.put("Scene", 0); - System.out.println(paramJson.toJSONString()); HttpEntity paramEntity = new StringEntity(paramJson.toJSONString(), Consts.UTF_8); httpPost.setEntity(paramEntity); @@ -631,4 +633,72 @@ public class WebWeixinApi { return null; } } + + /** + * 上传媒体文件 + * + * @return + */ + public JSONObject uploadMedia(HttpClient httpClient, + String passticket, + BaseRequest baseRequest, + String fromUserName, + String toUserName, + String dataTicket, + File file) { + try { + String url = new ST(PropertiesUtil.getProperty("webwx-url.uploadmedia_url")) + .render(); + + HttpPost httpPost = new HttpPost(url); + httpPost.setHeader("Content-type", ContentType.MULTIPART_FORM_DATA.toString()); + + long millis = System.currentTimeMillis(); + String contentTypeStr = new MimetypesFileTypeMap().getContentType(file); + ContentType contentType = ContentType.parse(contentTypeStr); + + JSONObject uploadmediarequest = new JSONObject(); + uploadmediarequest.put("UploadType", 2); + uploadmediarequest.put("BaseRequest", baseRequest); + uploadmediarequest.put("ClientMediaId", millis); + uploadmediarequest.put("TotalLen", file.length()); + uploadmediarequest.put("StartPos", 0); + uploadmediarequest.put("DataLen", file.length()); + uploadmediarequest.put("MediaType", 4); + uploadmediarequest.put("FromUserName", fromUserName); + uploadmediarequest.put("ToUserName", toUserName); + uploadmediarequest.put("FileMd5", DigestUtils.md5(new FileInputStream(file))); + + HttpEntity paramEntity = MultipartEntityBuilder.create() + .setMode(HttpMultipartMode.BROWSER_COMPATIBLE) + .addTextBody("id", StringUtil.getUuid(), ContentType.TEXT_PLAIN) + .addTextBody("name", file.getName(), ContentType.TEXT_PLAIN) + .addTextBody("type", contentTypeStr, ContentType.TEXT_PLAIN) + .addTextBody("lastModifieDate", millis + "", ContentType.TEXT_PLAIN) + .addTextBody("size", file.length() + "", ContentType.TEXT_PLAIN) + .addTextBody("mediatype", WechatUtil.getMediatype(contentType.getMimeType()), 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) + .addBinaryBody("filename", file, contentType, file.getName()) + .build(); + 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); + + JSONObject result = JSONObject.parseObject(res); + + return result; + } catch (Exception e) { + logger.error("上传媒体文件异常", e); + return null; + } + } } diff --git a/src/test/java/TestClass2.java b/src/test/java/TestClass2.java index 726277a..b6c6a4d 100644 --- a/src/test/java/TestClass2.java +++ b/src/test/java/TestClass2.java @@ -4,28 +4,23 @@ import com.hotlcc.wechat4j.api.WebWeixinApi; import com.hotlcc.wechat4j.handler.ReceivedMsgHandler; import com.hotlcc.wechat4j.model.ReceivedMsg; import com.hotlcc.wechat4j.model.UserInfo; -import com.hotlcc.wechat4j.model.WxMessage; public class TestClass2 { public static void main(String[] args) { -// WebWeixinApi api = new WebWeixinApi(); -// Wechat wechat = new Wechat(); -// wechat.setWebWeixinApi(api); -// wechat.addReceivedMsgHandler(new ReceivedMsgHandler() { -// @Override -// public void handleAllType(Wechat wechat, ReceivedMsg msg) { -// UserInfo contact = wechat.getContactByUserName(false, msg.getFromUserName()); -// System.out.println(contact.getRemarkName() + ":" + msg.getContent()); -// if ("李国栋".equals(contact.getRemarkName())) { -// JSONObject result = wechat.sendText("你的消息收到了", contact.getUserName()); -// System.out.println(result); -// } -// } -// }); -// wechat.autoLogin(); - WxMessage message=new WxMessage(); - message.setToUserName("1"); - message.setType(1); - System.out.println(JSONObject.toJSONString(message)); + WebWeixinApi api = new WebWeixinApi(); + Wechat wechat = new Wechat(); + wechat.setWebWeixinApi(api); + wechat.addReceivedMsgHandler(new ReceivedMsgHandler() { + @Override + public void handleAllType(Wechat wechat, ReceivedMsg msg) { + UserInfo contact = wechat.getContactByUserName(false, msg.getFromUserName()); + System.out.println(contact.getRemarkName() + ":" + msg.getContent()); + if ("李国栋".equals(contact.getRemarkName())) { + JSONObject result = wechat.sendText("你的消息收到了", contact.getUserName()); + System.out.println(result); + } + } + }); + wechat.autoLogin(); } }