您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關使用.net開發微信獲取AccessToken的源碼示例的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
AccessToken獲取方法
public static Access_token GetAccessToken() { string formatString = String.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", AppId, AppSecret); Access_token res = new Access_token(); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(formatString); request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); if (retString.IndexOf("7200") > 0) { Access_token token = new Access_token(); token = JsonHelper.ParseFromJson<Access_token>(retString); res.access_token = token.access_token; res.expires_in = token.expires_in; } return res; }
Access_token類結構
public class Access_token { public Access_token() { // //TODO:用于驗證Access_token是否過期實體 // } string _access_token; string _expires_in; /// <summary> /// 獲取到的憑證 /// </summary> public string access_token { get { return _access_token; } set { _access_token = value; } } /// <summary> /// 憑證有效時間,單位:秒 /// </summary> public string expires_in { get { return _expires_in; } set { _expires_in = value; } } }
JsonHelper.ParseFromJson方法
/// <summary> /// 將JSON對象轉換為Model /// </summary> /// <typeparam name="T"></typeparam> /// <param name="szJson"></param> /// <returns></returns> public static T ParseFromJson<T>(string szJson) { T obj = Activator.CreateInstance<T>(); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson))) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); return (T)serializer.ReadObject(ms); } }
感謝各位的閱讀!關于“使用.net開發微信獲取AccessToken的源碼示例”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。