.net微信开发 如何获取AccessToken
本文实例为大家分享了获取AccessToken的方法,供大家参考,具体内容如下
AccessToken获取方法
publicstaticAccess_tokenGetAccessToken() { stringformatString=String.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}",AppId,AppSecret); Access_tokenres=newAccess_token(); HttpWebRequestrequest=(HttpWebRequest)WebRequest.Create(formatString); request.Method="GET"; request.ContentType="text/html;charset=UTF-8"; HttpWebResponseresponse=(HttpWebResponse)request.GetResponse(); StreammyResponseStream=response.GetResponseStream(); StreamReadermyStreamReader=newStreamReader(myResponseStream,Encoding.GetEncoding("utf-8")); stringretString=myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); if(retString.IndexOf("7200")>0) { Access_tokentoken=newAccess_token(); token=JsonHelper.ParseFromJson(retString); res.access_token=token.access_token; res.expires_in=token.expires_in; } returnres; }
Access_token类结构
publicclassAccess_token { publicAccess_token() { // //TODO:用于验证Access_token是否过期实体 // } string_access_token; string_expires_in; //////获取到的凭证 /// publicstringaccess_token { get{return_access_token;} set{_access_token=value;} } //////凭证有效时间,单位:秒 /// publicstringexpires_in { get{return_expires_in;} set{_expires_in=value;} } }
JsonHelper.ParseFromJson方法
//////将JSON对象转换为Model /// ////// /// publicstaticTParseFromJson (stringszJson) { Tobj=Activator.CreateInstance (); using(MemoryStreamms=newMemoryStream(Encoding.UTF8.GetBytes(szJson))) { DataContractJsonSerializerserializer=newDataContractJsonSerializer(obj.GetType()); return(T)serializer.ReadObject(ms); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。