protected void Page_Load(object sender, EventArgs e)
{string padata = "username=用户名&pwd=md5的密码&imgcode=&f=json";//用于登录要发送的数据
string url = " ";//请求登录的URL try { CookieContainer cc = new CookieContainer();//接收缓存 byte[] byteArray = Encoding.UTF8.GetBytes(padata); // 转化 HttpWebRequest webRequest2 = (HttpWebRequest)WebRequest.Create(url); webRequest2.CookieContainer = cc; webRequest2.Method = "POST"; webRequest2.ContentType = "application/x-www-form-urlencoded";webRequest2.Referer = "https://mp.weixin.qq.com/";
webRequest2.ContentLength = byteArray.Length; Stream newStream = webRequest2.GetRequestStream(); // Send the data. newStream.Write(byteArray, 0, byteArray.Length); //写入参数 newStream.Close(); HttpWebResponse response2 = (HttpWebResponse)webRequest2.GetResponse(); StreamReader sr2=new StreamReader(response2.GetResponseStream(), Encoding.Default); string text2 = sr2.ReadToEnd();//此处用到了newtonsoft来序列化。大家可以不用这个,也可以自己手动写代码
RetInfo retinfo=Newtonsoft.Json.JsonConvert.DeserializeObject<RetInfo>(text2); string token = retinfo.ErrMsg.Split(new char[] { '&' })[2].Split(new char[]{'='})[1].ToString();//取得令牌 SendMessage(cc,token); } catch (Exception ex) { throw new Exception(ex.StackTrace); }}
public void SendMessage(CookieContainer cc, string token)
{
string padate = "type=1&content=要发送的内容(注意要先进行Url编码)&error=false&tofakeid=22108785&token=" + token + "&ajax=1";
string url = "";
byte[] byteArray = Encoding.UTF8.GetBytes(padate); // 转化
HttpWebRequest webRequest2 = (HttpWebRequest)WebRequest.Create(url);
webRequest2.CookieContainer = cc; //登录时得到的缓存
webRequest2.Referer = "=" + token + "&fromfakeid=22108785&msgid=&source=&count=20&t=wxm-singlechat&lang=zh_CN";
webRequest2.Method = "POST";
webRequest2.UserAgent = "Mozilla/5.0 (Windows NT 5.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1";
webRequest2.ContentType = "application/x-www-form-urlencoded";
webRequest2.ContentLength = byteArray.Length;
Stream newStream = webRequest2.GetRequestStream();
// Send the data.
newStream.Write(byteArray, 0, byteArray.Length); //写入参数
newStream.Close();
HttpWebResponse response2 = (HttpWebResponse)webRequest2.GetResponse();
StreamReader sr2 = new StreamReader(response2.GetResponseStream(), Encoding.Default);
string text2 = sr2.ReadToEnd();
Response.Write(text2);
}