.Net HttpClient 模拟登录微信公众平台发送消息
1.模拟登录
1 public WeiXinRetInfo ExecLogin(string name, string pass) 2 { 3 CookieContainer cc = new CookieContainer();//接收缓存 4 WeiXinRetInfo retinfo = null; 5 6 try 7 { 8 string password = Common.GetMd5Str32(pass).ToUpper(); 9 10 HttpClientHandler hchandler = new HttpClientHandler() 11 { 12 CookieContainer = cc 13 }; 14 15 HttpClient hclient = new HttpClient(hchandler); 16 hclient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36"); 17 hclient.DefaultRequestHeaders.Add("Referer", "https://mp.weixin.qq.com"); 18 //hclient.DefaultRequestHeaders.Add("Host", "mp.weixin.qq.com"); 19 //hclient.DefaultRequestHeaders.Add("ContentType", "application/x-www-form-urlencoded"); 20 //hclient.DefaultRequestHeaders.ExpectContinue = false; 21 22 HttpContent hcontent = new FormUrlEncodedContent(new Dictionary<string, string>() 23 { 24 {"username",name}, 25 {"pwd",password}, 26 {"imgcode",""}, 27 {"f","json"} 28 }); 29 30 //https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN 31 HttpResponseMessage hresponse = hclient.PostAsync(Wx_Const.LOGIN_URL, hcontent).Result; 32 33 hresponse.EnsureSuccessStatusCode(); 34 35 string str_response = hresponse.Content.ReadAsStringAsync().Result; 36 37 retinfo = Newtonsoft.Json.JsonConvert.DeserializeObject<WeiXinRetInfo>(str_response); 38 39 if (retinfo.base_resp.err_msg.Equals("ok")) 40 { 41 string token = retinfo.redirect_url.Split(new char[] { '&' })[2].Split(new char[] { '=' })[1].ToString();//取得令牌 42 lgin.CreateDate = DateTime.Now; 43 lgin.Token = token; 44 45 string[] strCookies = (string[])hresponse.Headers.GetValues("Set-Cookie"); 46 HttpClientCookies hcckis = new HttpClientCookies(); 47 hcckis.AddCookie(strCookies); 48 lgin.hcckis = hcckis; 49 50 lgin.LoginCookie = cc; 51 } 52 } 53 catch (Exception ex) 54 { 55 Console.WriteLine(string.Format("ExecLogin Exception[{0}]", ex.Message)); 56 //throw; 57 } 58 59 return retinfo; 60 }
2.新增图文消息(返回msgid),后续发送图文消息是用到
1 /// <summary> 2 /// 新增图文消息 3 /// </summary> 4 /// <returns></returns> 5 public CreateMsgRs AddWeixinImgTextMsg() 6 { 7 string str_url_add_appmsg = string.Format("https://mp.weixin.qq.com/cgi-bin/operate_appmsg?t=ajax-response&sub=create&type=10&token={0}&lang=zh_CN", this.lgif.Token); 8 9 //https://mp.weixin.qq.com/cgi-bin/operate_appmsg?t=ajax-response&sub=create&type=10&token={0}&lang=zh_CN 10 11 HttpClientHandler httpClientHandler = new HttpClientHandler() 12 { 13 CookieContainer = this.lgif.LoginCookie, 14 }; 15 16 HttpClient client = new HttpClient(httpClientHandler); 17 18 client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36"); 19 20 client.DefaultRequestHeaders.Add("Origin", "https://mp.weixin.qq.com"); 21 22 client.DefaultRequestHeaders.Add("Referer", string.Format("https://mp.weixin.qq.com/cgi-bin/appmsg?t=media/appmsg_edit&action=edit&type=10&lang=zh_CN&token={0}", this.lgif.Token)); 23 // 24 //client.DefaultRequestHeaders.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); 25 26 //client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded")); 27 28 //client.DefaultRequestHeaders.ty 29 30 string fileid0 = "204535166"; 31 32 UploadImgRs uploadImgRs = AddImg(); 33 34 if (uploadImgRs.base_resp.ErrMsg.Equals("ok")) 35 { 36 fileid0 = uploadImgRs.content; 37 } 38 39 HttpContent content = new FormUrlEncodedContent(new Dictionary<string, string>() 40 { 41 {"token",this.lgif.Token}, 42 {"lang","zh_CN"}, 43 {"f","json"}, 44 {"ajax","1"}, 45 {"random","0.9338385944720358"}, 46 {"AppMsgId",""}, 47 {"count","1"}, 48 {"title0","张静初出演电影版《三体》 获小说作者肯定"}, 49 {"content0","2015年,被媒体称为中国“科幻元年”,多部科幻片启动了拍摄计划,《三体》当然是最受瞩目的,宣布的开机消息如是说“影片由小说原作者刘慈欣出任监制、游族影业CEO孔二狗担任总制片人、新锐导演张番番历经三年苦心筹备出任影片导演,台前众多国内实力派艺人担纲出演,幕后则由国际团队承担起拍摄、特效等重任,力求将本片打造成一部制作精良、高度还原的史诗级国产科幻片开山之作。”看着这依然模棱两可的说辞,网友们忧心忡忡,去年一片“求不渣”的请求声再起"}, 50 {"digest0","2015年,被媒体称为中国“科幻元年”,多部科幻片启动了拍摄计划,《三体》当然是最受瞩目的"}, 51 {"author0","李晓婕 仲敏"}, 52 {"fileid0",fileid0},//图片文件ID 53 {"show_cover_pic0","1"}, 54 {"shortvideofileid0",""}, 55 {"copyright_type0","0"}, 56 {"can_reward0","0"}, 57 {"reward_wording0",""}, 58 {"sourceurl0",""}, 59 {"vid",""}, 60 //{"preusername",""} 61 }); 62 HttpResponseMessage response = client.PostAsync(str_url_add_appmsg, content).Result; 63 //{"base_resp":{"ret":0,"err_msg":"ok"},"ret":"0","msg":"","appMsgId":204514536} 64 string s = response.Content.ReadAsStringAsync().Result; 65 66 CreateMsgRs cmrs = Newtonsoft.Json.JsonConvert.DeserializeObject<CreateMsgRs>(s); 67 68 return cmrs; 69 }
3.获取图文列表
1 /// <summary> 2 /// 获取图文消息列表 3 /// </summary> 4 /// <returns></returns> 5 public WeixinImgTextMsg GetImgTextList() 6 { 7 WeixinImgTextMsg wxImgText = null; 8 9 string str_url_get_list = string.Format("https://mp.weixin.qq.com/cgi-bin/appmsg?type=10&action=list&begin=0&count=10&f=json&token={0}&lang=zh_CN&token={0}&lang=zh_CN&f=json&ajax=1&random={1}", this.lgif.Token, "0.18148761289194222"); 10 11 HttpClientHandler httpClientHandler = new HttpClientHandler() 12 { 13 CookieContainer = this.lgif.LoginCookie, 14 }; 15 16 HttpClient client = new HttpClient(httpClientHandler); 17 18 client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36"); 19 20 HttpResponseMessage response = client.GetAsync(str_url_get_list).Result; 21 22 string s = response.Content.ReadAsStringAsync().Result; 23 24 wxImgText = Newtonsoft.Json.JsonConvert.DeserializeObject<WeixinImgTextMsg>(s); 25 26 return wxImgText; 27 28 }
4.获取订阅用户
1 /// <summary> 2 /// 获取fakeid 3 /// </summary> 4 /// <returns></returns> 5 public ArrayList SubscribeMP() 6 { 7 string token = this.loginInfo.Token; 8 9 string str_url_sendmsg = string.Format("https://mp.weixin.qq.com/cgi-bin/contactmanage?t=user/index&pagesize=10&pageidx=0&type=0&groupid=0&token={0}&lang=zh_CN", token); 10 11 try 12 { 13 HttpClientHandler hchandler = new HttpClientHandler() 14 { 15 CookieContainer = this.loginInfo.LoginCookie 16 }; 17 18 HttpClient hclient = new HttpClient(hchandler); 19 20 hclient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36"); 21 22 HttpResponseMessage response = hclient.GetAsync(str_url_sendmsg).Result; 23 24 response.EnsureSuccessStatusCode(); 25 26 string str_response_html = response.Content.ReadAsStringAsync().Result; 27 28 MatchCollection mc; 29 30 //由于此方法获取过来的信息是一个【html网页】所以此处使用了正则表达式,注意:(此正则表达式只是获取了fakeid的信息如果想获得一些其他的信息修改此处的正则表达式就可以了。) 31 Regex r = new Regex("\"id\"\\:\\d+,\"nick_name\""); //定义一个Regex对象实例 32 mc = r.Matches(str_response_html); 33 Int32 friendSum = mc.Count; //好友总数 34 35 string fackID = ""; 36 37 ArrayList fackID1 = new ArrayList(); 38 39 for (int i = 0; i < friendSum; i++) 40 { 41 //"id":208989515,"nick_name" 42 fackID = mc[i].Value.Replace(",\"nick_name\"", "").Split(new char[] { ':' })[1]; 43 fackID = fackID.Replace("\"", "").Trim(); 44 fackID1.Add(fackID); 45 } 46 47 return fackID1; 48 } 49 catch (Exception ex) 50 { 51 throw new Exception(ex.StackTrace); 52 } 53 }
5.发送消息
1 /// <summary> 2 /// 发送消息 3 /// </summary> 4 /// <param name="Message"></param> 5 /// <param name="fakeid"></param> 6 public SendMsgRs SendWxMessage(Wx_MsgType WxMsgType, string Message, string fakeid, string msgIdOrFileId) 7 { 8 SendMsgRs sendMsgRs = new SendMsgRs(); 9 10 string token = this.loginInfo.Token; 11 12 string str_url_sendmsg = string.Format("https://mp.weixin.qq.com/cgi-bin/singlesend?t=ajax-response&f=json&token={0}&lang=zh_CN", token); 13 14 try 15 { 16 HttpClientHandler hchandler = new HttpClientHandler() 17 { 18 CookieContainer = this.loginInfo.LoginCookie 19 }; 20 21 //HttpContent hcontent = new FormUrlEncodedContent(new Dictionary<string, string>() 22 //{ 23 // {"type","1"}, 24 // {"content",Message}, 25 // {"error","false"}, 26 // {"tofakeid",fakeid}, 27 // {"token",token}, 28 // {"ajax","1"}, 29 //}); 30 31 HttpContent hcontent = new FormUrlEncodedContent(this.GetMsgContentByMsgType(WxMsgType, msgIdOrFileId, Message, fakeid)); 32 33 HttpClient hclient = new HttpClient(hchandler); 34 35 hclient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36"); 36 hclient.DefaultRequestHeaders.Add("Referer", string.Format("https://mp.weixin.qq.com/cgi-bin/singlemsgpage?token={0}&fromfakeid={1}&msgid=&source=&count=20&t=wxm-singlechat&lang=zh_CN", token, fakeid)); 37 38 39 HttpResponseMessage response = hclient.PostAsync(str_url_sendmsg, hcontent).Result; 40 41 response.EnsureSuccessStatusCode(); 42 43 string s = response.Content.ReadAsStringAsync().Result; 44 45 sendMsgRs = Newtonsoft.Json.JsonConvert.DeserializeObject<SendMsgRs>(s); 46 } 47 catch (Exception ex) 48 { 49 throw; 50 } 51 return sendMsgRs; 52 }
6.新增图文消息是,需要上传一张封面图片,返回fileid
1 /// <summary> 2 /// 3 /// </summary> 4 public UploadImgRs AddImg() 5 { 6 UploadImgRs uUploadImgRs = new UploadImgRs(); 7 8 string str_rs = string.Empty; 9 10 //ticket_id,ticket可从一下地址解析获取 11 //https://mp.weixin.qq.com/cgi-bin/settingpage?t=setting/index&action=index&token=1985674500&lang=zh_CN 12 //https://mp.weixin.qq.com/cgi-bin/home?t=home/index&lang=zh_CN&token=1437387422 13 //string ticket_id = "gh_982977c20410"; 14 //string ticket = "62b2f4612b5b2f30583b517a21a1b76ffb8a7711"; 15 16 string ticket_id = this.lgif.user_name; 17 string ticket = this.lgif.CurTicket; 18 19 string str_url_uploadimg = string.Format("https://mp.weixin.qq.com/cgi-bin/filetransfer?action=upload_material&f=json&writetype=doublewrite&groupid=1&ticket_id={0}&ticket={1}&token={2}&lang=zh_CN", ticket_id, ticket, this.lgif.Token); 20 21 HttpClientHandler httpClientHandler = new HttpClientHandler() 22 { 23 CookieContainer = this.lgif.LoginCookie, 24 }; 25 26 using (HttpClient client = new HttpClient(httpClientHandler)) 27 { 28 client.DefaultRequestHeaders.Add("Connection", "keep-alive"); 29 client.DefaultRequestHeaders.Add("Origin", "https://mp.weixin.qq.com"); 30 client.DefaultRequestHeaders.Add("Referer", "https://mp.weixin.qq.com/cgi-bin/filepage?type=2&begin=0&count=12&t=media/img_list&token=" + this.lgif.Token + "&lang=zh_CN"); 31 //client.DefaultRequestHeaders.Add("", ""); 32 //client.DefaultRequestHeaders.Add("", ""); 33 //client.DefaultRequestHeaders.Add("", ""); 34 //client.DefaultRequestHeaders.Add("", ""); 35 client.DefaultRequestHeaders.ExpectContinue = false; 36 37 client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36"); 38 39 using (MultipartFormDataContent content = new MultipartFormDataContent()) 40 { 41 //******************************************* 42 //******************************************* 43 //!!!!!!!!!非常重要的地方,致命重要的设置!!!!!!!!!! 44 //******************************************* 45 //******************************************* 46 var boundaryValue = content.Headers.ContentType.Parameters.FirstOrDefault(p => p.Name == "boundary"); 47 boundaryValue.Value = boundaryValue.Value.Replace("\"", String.Empty); 48 //******************************************* 49 //******************************************* 50 //!!!!!!!!!非常重要的地方,致命重要的设置!!!!!!!!!! 51 //******************************************* 52 //******************************************* 53 54 string str_file_path = Environment.CurrentDirectory + @"\ac345982b2b7d0a2f9d24887c9ef76094b369a95.jpg"; 55 FileStream fileStream = File.OpenRead(str_file_path); 56 57 StringContent sc_id = new StringContent("WU_FILE_0"); 58 sc_id.Headers.Remove("Content-Type"); 59 content.Add(sc_id, "\"id\""); 60 //content.Add(new StringContent("WU_FILE_0"), "\"id\""); 61 62 StringContent sc_name = new StringContent("2b5906a9da28784e4a36d6db.jpg"); 63 sc_name.Headers.Remove("Content-Type"); 64 content.Add(sc_name, "\"name\""); 65 //content.Add(new StringContent("2b5906a9da28784e4a36d6db.jpg"), "\"name\""); 66 67 StringContent sc_type = new StringContent("image/jpeg"); 68 sc_type.Headers.Remove("Content-Type"); 69 content.Add(sc_type, "\"type\""); 70 //content.Add(new StringContent("image/jpeg"), "\"type\""); 71 72 StringContent sc_lastModifiedDate = new StringContent("Thu Mar 19 2015 17:11:58 GMT+0800 (中国标准时间)"); 73 sc_lastModifiedDate.Headers.Remove("Content-Type"); 74 content.Add(sc_lastModifiedDate, "\"lastModifiedDate\""); 75 //content.Add(new StringContent("Thu Mar 19 2015 17:11:58 GMT+0800 (中国标准时间)"), "\"lastModifiedDate\""); 76 77 StringContent sc_size = new StringContent(Convert.ToInt32(fileStream.Length).ToString()); 78 sc_size.Headers.Remove("Content-Type"); 79 content.Add(sc_size, "\"size\""); 80 //content.Add(new StringContent(Convert.ToInt32(fileStream.Length).ToString()), "\"size\""); 81 82 83 //*************************** 84 var streamContent = new StreamContent(fileStream); 85 86 //Content-Disposition: form-data; name="file"; filename="2b5906a9da28784e4a36d6db.jpg" 87 //Content-Type: image/jpeg 88 //Content-Disposition: form-data; name="file"; filename="2b5906a9da28784e4a36d6db.jpg" 89 //Content-Type: image/jpeg 90 streamContent.Headers.Add("Content-Disposition", "form-data; name=\"file\"; filename=\"" + Path.GetFileName(str_file_path) + "\""); 91 streamContent.Headers.Add("Content-Type", "image/jpeg"); 92 93 content.Add(streamContent, "file", Path.GetFileName(str_file_path)); 94 95 HttpResponseMessage response = client.PostAsync(str_url_uploadimg, content).Result; 96 97 response.EnsureSuccessStatusCode(); 98 99 string s = str_rs = response.Content.ReadAsStringAsync().Result; 100 101 uUploadImgRs = Newtonsoft.Json.JsonConvert.DeserializeObject<UploadImgRs>(s); 102 } 103 104 105 106 //返回结果 107 //{"base_resp":{"ret":0,"err_msg":"ok"},"location":"bizfile","type":"image","content":"204535433"} 108 } 109 110 return uUploadImgRs; 111 }
以上代码仅是大概流程,又问提的可以留言我.