JAVA模拟微信发送文件给好友/群


通过google开发者模式抓取https://file2.wx.qq.com/cgi-bin/mmwebwx-bin/webwxuploadmedia?f=json这条请求可以清楚的看到参数,有了这个参数我们就可以使用java中的httpsurlConnection接口进行模拟。

代码示例

    package com.yh.util.network;import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import com.yh.util.json.JSONException;
import com.yh.util.json.JSONObject;public class SendFileUtils {public static String upload(String filePath,String uIn,String sId,String sKey,int fileType) {
//        // set https proxy
//        System.setProperty("https.proxyHost", "127.0.0.1");
//        System.setProperty("https.proxyPort", "8888");String response = null;InputStream inputStream = null;InputStreamReader inputStreamReader = null;BufferedReader bufferedReader = null;HttpsURLConnection conn = null;try {File file = new File(filePath);if (!file.exists() || !file.isFile()) {throw new IOException("文件不存在");}//请求头参数String boundary = "----WebKitFormBoundary6oVvR66QUmo1TkXD"; //区分每个参数之间String freFix = "--";String newLine = "\r\n";URL urlObj = new URL("https://file2.wx.qq.com/cgi-bin/mmwebwx-bin/webwxuploadmedia?f=json");conn = (HttpsURLConnection) urlObj.openConnection();conn.setRequestMethod("POST");conn.setDoOutput(true);  conn.setDoInput(true);  conn.setUseCaches(false);conn.setRequestProperty("Accept", "*/*");conn.setRequestProperty("Accept-Encoding", "gzip, deflate");conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");conn.setRequestProperty("Cache-Control", "no-cache");conn.setRequestProperty("Connection", "Keep-Alive");conn.setRequestProperty("Content-Length", Long.toString(file.length()));conn.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);conn.setRequestProperty("Host", "file2.wx.qq.com");conn.setRequestProperty("Origin", "https://wx2.qq.com");conn.setRequestProperty("Pragma", "no-cache");conn.setRequestProperty("Referer", "https://wx2.qq.com/");conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0");// 请求主体StringBuffer sb = new StringBuffer();sb.append(freFix+boundary).append(newLine); //这里注意多了个freFix,来区分去请求头中的参数sb.append("Content-Disposition: form-data; name=\"name\"");sb.append(newLine).append(newLine);sb.append(file.getName()).append(newLine);sb.append(freFix+boundary).append(newLine);sb.append("Content-Disposition: form-data; name=\"lastModifiedDate\"");sb.append(newLine).append(newLine);sb.append("Tue Sep 29 2015 13:47:39 GMT+0800").append(newLine);sb.append(freFix+boundary).append(newLine);sb.append("Content-Disposition: form-data; name=\"size\"");sb.append(newLine).append(newLine);sb.append(file.length()).append(newLine);sb.append(freFix+boundary).append(newLine);sb.append("Content-Disposition: form-data; name=\"mediatype\"");sb.append(newLine).append(newLine);sb.append("doc").append(newLine);sb.append(freFix+boundary).append(newLine);sb.append("Content-Disposition: form-data; name=\"uploadmediarequest\"");sb.append(newLine).append(newLine);sb.append("{\"BaseRequest\":{\"Uin\":"+uIn+",\"Sid\":\""+sId+"\",\"Skey\":\"@"+sKey+"\",\"DeviceID\":\"e823469202135602\"},\"ClientMediaId\": "+System.currentTimeMillis()+",\"TotalLen\":"+file.length()+",\"StartPos\":0,\"DataLen\":"+file.length()+",\"MediaType\":4}").append(newLine);sb.append(freFix+boundary).append(newLine);sb.append("Content-Disposition: form-data; name=\"type\"");sb.append(newLine).append(newLine);sb.append("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet").append(newLine);sb.append(freFix+boundary).append(newLine);sb.append("Content-Disposition: form-data; name=\"filename\"; filename=\""+file.getName()+"\"");sb.append(newLine);sb.append("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");sb.append(newLine).append(newLine);OutputStream outputStream = new DataOutputStream(conn.getOutputStream());outputStream.write(sb.toString().getBytes("utf-8"));//写入请求参数DataInputStream dis = new DataInputStream(new FileInputStream(file));  int bytes = 0;  byte[] bufferOut = new byte[1024];  while ((bytes = dis.read(bufferOut)) != -1) {  outputStream.write(bufferOut,0,bytes);//写入图片}outputStream.write(newLine.getBytes());outputStream.write((freFix+boundary+freFix+newLine).getBytes("utf-8"));//标识请求数据写入结束dis.close();  outputStream.close();//读取响应信息inputStream = conn.getInputStream();inputStreamReader = new InputStreamReader(inputStream, "UTF-8");bufferedReader = new BufferedReader(inputStreamReader);String str = null;StringBuffer buffer = new StringBuffer();while ((str = bufferedReader.readLine()) != null) {buffer.append(str);}response = buffer.toString();} catch (Exception e) {e.printStackTrace();}finally{if(conn!=null){conn.disconnect();}try {bufferedReader.close();inputStreamReader.close();inputStream.close();} catch (IOException execption) {}}return response;}public static void send(String filePath,String cookie,String uIn,String sId,String sKey,String fileName,String fromUserName,String toUserName) throws JSONException{filePath = "C:/Users/klay/Desktop/helloWorld.xlsx";uIn = "1";sId = "1";sKey = "11";fileName = "helloWorld.xls";int mediaType = 4;String result = upload(filePath,uIn,sId,sKey,mediaType);//执行图片上传,返回流媒体id。PS:微信网页版中的发送文件/图片/等分为两步1.上传到服务器拿到返回的mediaId,2.发送通知消息JSONObject json = new JSONObject(result);String mediaId = json.get("MediaId").toString();System.out.println(json.get("MediaId"));//发送图片Long currentTimeMillis = System.currentTimeMillis();String jsonParamsByFile = "{\"BaseRequest\":{\"Uin\":"+uIn+",\"Sid\":\""+sId+"\",\"Skey\":\"@"+sKey+"\",\"DeviceID\":\"e640359774620125\"},\"Msg\":{\"Type\":6,\"Content\":\"<appmsg appid=\'wxeb7ec651dd0aefa9\' sdkver=\'\'><title>"+fileName+"</title><des></des><action></action><type>6</type><content></content><url></url><lowurl></lowurl><appattach><totallen>9879</totallen><attachid>"+mediaId+"</attachid><fileext>xlsx</fileext></appattach><extinfo></extinfo></appmsg>\",\"FromUserName\":\"@"+fromUserName+"\",\"ToUserName\":\"@@"+toUserName+"\",\"LocalID\":\""+currentTimeMillis+"\",\"ClientMsgId\":\""+currentTimeMillis+"\"}}";cookie  = "";System.out.println(jsonParamsByFile);String url = "https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxsendappmsg?fun=async&f=json&lang=zh_CN";  HttpClient client = new DefaultHttpClient();HttpPost post = new HttpPost(url);post.addHeader(new BasicHeader("cookie", cookie));//发送文件必须设置,cookietry {StringEntity s = new StringEntity(jsonParamsByFile);post.setEntity(s);HttpResponse res = client.execute(post);if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){HttpEntity entity = res.getEntity();System.out.println(EntityUtils.toString(entity, "utf-8"));}} catch (Exception e) {e.printStackTrace();}   }

}

里面的HttpClient需要4.3的jar。如果要发送图片那么根据请求的参数改一下就行了,只是send方法里的jsonParamsByFile 需要改一下,整个过程都是https请求,但是不要证书也可以请求成功。

模拟微信发送文件给好友/群相关推荐

  1. android发送文件到微信,微信怎么发送文件给别人 微信发送文件给好友方法

    微信是我们目前日常生活必不可少的社交软件,很多小伙伴每天都坚持刷朋友圈,关注身边人最新的动态,那么在之前的老版微信中,没有文件发送功能,而在今天微信团队正式更新微信版本(安卓6.5.24版本),目前已 ...

  2. UI自动化控制微信发送文件【解决了一个无人回答的难题,Pywin32设置文件到剪切板】

    大家好,我是小小明.前面我在<UI自动化控制PC版微信>该系列文中更新了控制微信发送图片的方法.根据部分群友实际工作的需要,本文将分享如何控制微信发送文件. 专栏链接:https://bl ...

  3. 微信怎么和计算机发送文件格式,用微信怎么发送文件 手机微信发送文件、视频方法图文详解...

    微信火爆程度已经明显超过qq了,那么你知道微信除了飞好友发送图片.视频外还能发送文件,今天小编就为大家分享手机微信发送文件方法图文详解,如何用微信将电脑.手机上的文件发送给好友. 微信怎么添加自定义表 ...

  4. kettle实现企业微信发送文件

    kettle实现企业微信发送文件 用途 通过kettle中嵌入java代码,实现企业微信发送文件. 实现效果 脚本总览 转换属性: 生成记录 用于模拟待上传的文件 Java代码 java代码参考:ht ...

  5. 电脑微信发送文件总显示“文件被占用,无法发送,请重新选择。”

    奇怪的问题 在微信发送文件多次提醒时,查看了文件被占用情况,发现并未被占用, 为了解决疑惑,尝试多方发送 同一个文件,发送钉钉就完全没有问题,发送微信却总提示"文件占用,无法发送" ...

  6. 【银河麒麟桌面操作系统微信发送文件失败-问题分析及解决方案】

    银河麒麟桌面操作系统微信发送文件失败-问题分析及解决方案 1.问题描述 银河麒麟桌面操作系统微信发送文件失败,提示文件为空文件,检查发现文件并非空文件. 2.问题分析排查 2.1微信版本信息:已是最新 ...

  7. Python实现微信发送文件实例

    新建Python文件:wx_file.py,代码如下 # -*- coding: utf-8 -*- # @Author : CxiuM # @Time : 2023-07-06 10:12 # @N ...

  8. js可以打开mat文件吗_企业微信最大可以传多大文件?企业微信发送文件有限制吗?...

    使用企业微信营销管理时,可以让我们的工作交流沟通更加高效便捷,在日常办公中,我们时常有传文件的需求,这时就可以使用企业微信进行文件传输,那么你知道企业微信最大可以传多大文件吗?企业微信发文件会有限制吗 ...

  9. PC微信逆向:分析微信发送文件call

    文章目录 发送文件call的结构体参数分析 组合数据call的分析 定位发送文件的call 接上一篇文章,PCXX逆向:发送与接收消息的分析与代码实现:https://blog.csdn.net/qq ...

最新文章

  1. Nagios监控之9:利用sendmail使用第三方SMTP服务发送邮件报警
  2. qtiplot编译失败linux,在macOS上安装 qtiplot 免费版
  3. ajax asp后台获取不到post数据,jQuery AJAX调用将数据发布到ASP.Net页面(不是Get但POST)...
  4. C语言程序练习- L1-040 最佳情侣身高差 (10分)
  5. 在EF4.0中获取ObjectContext的数据库连接字符串
  6. 同时画多个饼图_手帐术 | 这个神奇饼图里,藏着时间管理的小秘诀
  7. 《走遍中国》珍藏版(十)
  8. 计算机硬件知识竞赛题库,电脑知识竞赛题库.pdf
  9. oracle 驱动表提示错误代码,oracle驱动表以及如何确定驱动表
  10. ^_-诚征BLOG友情连接
  11. 徐起预热realme Q5系列:骁龙870+80W快充 新一代千元机皇
  12. Qt6程序打包(如何解决Qt程序在其他电脑上无法运行的问题)
  13. 开放源代码现象的经济基础
  14. 2022西工大网络安全知识竞赛赛后回顾资料
  15. 常见网络爬虫反爬机制与反爬机制的解决方案
  16. C++中按名次排序的两个实现方式
  17. fabs linux头文件,fabs(c语言fabs函数用法求精度)
  18. SAP中货物移动库位权限管理测试
  19. 微信小程序| Ngork内网传统+后台API通信例子
  20. python离线安装selenium_python34怎么离线安装selenium

热门文章

  1. 为什么越学反而越蠢?碎片化学习是个骗局
  2. Microsoft IExpress:微软自带的安装程序包制作工具
  3. notes-ThinkCMF视频教程 第一期(网易云课堂)
  4. 俄罗斯商标注册步骤是
  5. 浅谈微信小程序的功能定位和使用场景
  6. Google Docs API 介绍
  7. c语言中fact函数怎么调用,C语言程序题: 1、编写一个求n!的函数fact(n),要求fact函数分别用递归和非递归两种方法实现...
  8. 学计算机励志名言,程序员励志格言
  9. 什么是cherry-pick
  10. STC51单片机数码管显示程序和仿真