这篇文章给大家分享的是有关使用.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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。