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

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));//发送文件必须设置,cookie

        try {
            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请求,但是不要证书也可以请求成功。

评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值