#region 請求Url,不發送數據 /// /// 請求Url,不發送數據 /// public static string RequestUrl(string url) { return RequestUrl(url, "POST"); } #endregion #region 請求Url,不... ...
#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 //獲取Openid public 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"); }