HttpHelper模拟post和get请求
public class HttpHelper { /// <summary> /// 模拟post请求 /// </summary> /// <param name="url">url</param> /// <param name="data">数据</param> /// <returns></returns> public static string HttpPost(string url, string data) { HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; CookieContainer cookies = new CookieContainer(); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.CookieContainer = cookies; Stream resStream = request.GetRequestStream(); StreamWriter StreamWriter = new StreamWriter(resStream, Encoding.UTF8); StreamWriter.Write(data); StreamWriter.Close(); HttpWebResponse response = request.GetResponse() as HttpWebResponse; response.Cookies = cookies.GetCookies(response.ResponseUri); Stream responseStream = response.GetResponseStream(); StreamReader reader = new StreamReader(responseStream, Encoding.UTF8); string result = reader.ReadToEnd(); responseStream.Close(); reader.Close(); return result; } /// <summary> /// 模拟get请求 /// </summary> /// <param name="url"></param> /// <returns></returns> public static string HttpGet(string url) { HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8"; HttpWebResponse response = request.GetResponse() as HttpWebResponse; Stream responceStream = response.GetResponseStream(); StreamReader reader = new StreamReader(responceStream,Encoding.UTF8); string result = reader.ReadToEnd(); responceStream.Close(); reader.Close(); return result; } }
这个是我自己修改的获取token为了不让调用token的api到达每日最高次数,使用的时候需要改下xml配置文件的路径,附上路径xml文档
public class WeiXinHelper { /// <summary> /// 通过appID和appsecret获取Access_token /// </summary> /// <returns></returns> public static string GetAccess_token() { string AccessToken = ""; //获取配置文件中存好的accesstoken和有效时间 // 读取XML文件中的数据,并显示出来 ,注意文件路径 // StreamReader str = new StreamReader(filepath, System.Text.Encoding.UTF8); XmlDocument xml = new XmlDocument(); //xml.Load(@"D:weixinWebSite1WeiXinDemo oken.xml"); xml.Load(@"D:我的工作备注WebSite1WeiXinDemo oken.xml"); DateTime tokenTime = Convert.ToDateTime(xml.DocumentElement.SelectSingleNode("token_time").InnerText); if (DateTime.Now > tokenTime) { string appid = ConfigurationManager.AppSettings["appid"]; string appsecret = ConfigurationManager.AppSettings["appsecret"]; string url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid, appsecret); string AccessTokenList = GetPage(url, ""); accessToken act = JsonHelper.JsonDeSerializer<accessToken>(AccessTokenList); xml.DocumentElement.SelectSingleNode("token_time").InnerText = DateTime.Now.AddHours(2).ToString(); xml.DocumentElement.SelectSingleNode("access_token").InnerText = act.access_token; // xml.Save(@"D:weixinWebSite1WeiXinDemo oken.xml"); xml.Save(@"D:我的工作备注WebSite1WeiXinDemo oken.xml"); } AccessToken = xml.DocumentElement.SelectSingleNode("access_token").InnerText; return AccessToken; } /// <summary> /// 获取网页授权之后的token信息 /// </summary> /// <returns></returns> public static codeResult GetAccess_token_sq(string code) { codeResult codeInfo = new codeResult(); //获取配置文件中存好的accesstoken和有效时间 // 读取XML文件中的数据,并显示出来 ,注意文件路径 // StreamReader str = new StreamReader(filepath, System.Text.Encoding.UTF8); XmlDocument xml = new XmlDocument(); //xml.Load(@"D:weixinWebSite1WeiXinDemo oken.xml"); xml.Load(@"D:我的工作备注WebSite1WeiXinDemo oken.xml"); DateTime tokenTime = Convert.ToDateTime(xml.DocumentElement.SelectSingleNode("token_time_sq").InnerText); if (DateTime.Now > tokenTime) { string appid = ConfigurationManager.AppSettings["appid"]; string appsecret = ConfigurationManager.AppSettings["appsecret"]; string url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appid, appsecret, code); string info = HttpHelper.HttpGet(url); codeInfo = JsonHelper.JsonDeSerializer<codeResult>(info); xml.DocumentElement.SelectSingleNode("token_time_sq").InnerText = DateTime.Now.AddHours(2).ToString(); xml.DocumentElement.SelectSingleNode("access_token_sq").InnerText = codeInfo.access_token; xml.DocumentElement.SelectSingleNode("refresh_token").InnerText = codeInfo.refresh_token; xml.DocumentElement.SelectSingleNode("openid").InnerText = codeInfo.openid; xml.DocumentElement.SelectSingleNode("scope").InnerText = codeInfo.scope; // xml.Save(@"D:weixinWebSite1WeiXinDemo oken.xml"); xml.Save(@"D:我的工作备注WebSite1WeiXinDemo oken.xml"); } else { codeInfo.access_token = xml.DocumentElement.SelectSingleNode("access_token_sq").InnerText; codeInfo.refresh_token = xml.DocumentElement.SelectSingleNode("refresh_token").InnerText; codeInfo.openid = xml.DocumentElement.SelectSingleNode("openid").InnerText; codeInfo.scope = xml.DocumentElement.SelectSingleNode("scope").InnerText; } return codeInfo; } public static string GetPage(string posturl, string postData) { Stream outstream = null; Stream instream = null; StreamReader sr = null; HttpWebResponse response = null; HttpWebRequest request = null; Encoding encoding = Encoding.UTF8; byte[] data = encoding.GetBytes(postData); // 准备请求... try { // 设置参数 request = WebRequest.Create(posturl) as HttpWebRequest; CookieContainer cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; request.AllowAutoRedirect = true; request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; outstream = request.GetRequestStream(); outstream.Write(data, 0, data.Length); outstream.Close(); //发送请求并获取相应回应数据 response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才开始向目标网页发送Post请求 instream = response.GetResponseStream(); sr = new StreamReader(instream, encoding); //返回结果网页(html)代码 string content = sr.ReadToEnd(); string err = string.Empty; return content; } catch (Exception ex) { return string.Empty; } } }
所涉及的类
所涉及到的类 public class codeResult { public string access_token; public string expires_in; public string refresh_token; public string openid; public string scope; } public class JsonHelper { public static string JsonSerializer<T>(T t) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); using (MemoryStream ms = new MemoryStream()) { ser.WriteObject(ms, t); string jsonString = Encoding.UTF8.GetString(ms.ToArray()); return jsonString; } } // 从一个Json串生成对象信息 public static T JsonDeSerializer<T>(string json) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T)); using(MemoryStream mStream = new MemoryStream(Encoding.UTF8.GetBytes(json))) { return (T)serializer.ReadObject(mStream); } } } [Serializable] public class accessToken { public string access_token; public string expires_in; }
webConfig的appId和appsecret
<appSettings> <add key="appId" value="wx44bc......d905d" /> <add key="appsecret" value="2328cb.......13f7764a604a9" /> </appSettings>
<?xml version="1.0" encoding="utf-8"?> <xml> <access_token>xpcdR9i1KEYXpZRfA3YG3sap-MKGASjCAtNvb-kt9b8HJUWYWynUZ2K6oAHjNUmx-cwwkoDhHN2ajVdzr-twATldqlXwaFJ0VOYiABAEXH</access_token> <token_time>2017/2/13 18:16:41</token_time> <!--网页授权之后的token--> <access_token_sq>yIc4JI3qK09mPavE8opJmd4rLnOmx0WLcmAGx4-WptfEXf9CMXBVrrboCyWQqCOUll2Dv_fA</access_token_sq> <token_time_sq>2017/2/13 18:03:12</token_time_sq> <refresh_token>d_fticIKUu22Gk4grCZEIw3M7x47umIUAZ1Ss9lf-TMKXChrFHzRigAVGEE1qTv_PF41XFcVULWW4Ydg5-cHW51o</refresh_token> <openid>ohCfnwE0QhJzxbd2-qPMzk</openid> <scope>snsapi_userinfo</scope> </xml>