本文實例為大家分享了C# wx獲取token的具體代碼,供大家參考,具體內容如下
#region 請求Url,不發送數據/// <summary>/// 請求Url,不發送數據/// </summary>public static string RequestUrl(string url){return RequestUrl(url, "POST");}#endregion#region 請求Url,不發送數據/// <summary>/// 請求Url,不發送數據/// </summary>public static string RequestUrl(string url, string method){// 設置參數var request = WebRequest.Create(url) as HttpWebRequest;var cookieContainer = new CookieContainer();request.CookieContainer = cookieContainer;request.AllowAutoRedirect = true;request.Method = method;request.ContentType = "text/html";request.Headers.Add("charset", "utf-8");//發送請求并獲取相應回應數據var response = request.GetResponse() as HttpWebResponse;//直到request.GetResponse()程序才開始向目標網頁發送Post請求Stream responseStream = response.GetResponseStream();var sr = new StreamReader(responseStream, Encoding.UTF8);//返回結果網頁(html)代碼string content = sr.ReadToEnd();return content;}#endregion #region 獲取Json字符串某節點的值/// <summary>/// 獲取Json字符串某節點的值/// </summary>public static string GetJsonValue(string jsonStr, string key){string result = string.Empty;if (!string.IsNullOrEmpty(jsonStr)){key = "/"" + key.Trim('"') + "/"";int index = jsonStr.IndexOf(key) + key.Length + 1;if (index > key.Length + 1){//先截逗號,若是最后一個,截"}"號,取最小值int end = jsonStr.IndexOf(',', index);if (end == -1){end = jsonStr.IndexOf('}', index);}result = jsonStr.Substring(index, end - index);result = result.Trim(new [] {'"', ' ', '/"'}); //過濾引號或空格}}return result;}#endregion#region 驗證Token是否過期/// <summary>/// 驗證Token是否過期/// </summary>public static bool TokenExpired(string access_token){string jsonStr =RequestUrl(string.Format("https://api.weixin.qq.com/cgi-bin/menu/get?access_token={0}",access_token));if (GetJsonValue(jsonStr, "errcode") == "42001"){return true;}return false;}#endregion#region 獲取Token/// <summary>/// 獲取Token/// </summary>public static string GetToken(string appid, string secret){string strJson =RequestUrl(string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}",appid, secret));return GetJsonValue(strJson, "access_token");}#endregion//獲取Openidpublic static string GetOpenId(string appid, string secret, string code){string strJson =RequestUrl(string.Format("https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code",appid, secret, code));//LogUtil.WriteLog(strJson);return GetJsonValue(strJson, "openid");}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答