本文实例为大家分享了获取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介绍的详细内容。