微信开发 获取AccessToken

2018-06-22 07:45:58来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

获取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);
    }
}

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:编译器错误消息: CS0234: 命名空间“System.Web”中不存在类型或

下一篇:上机练习1 更新会员积分