C#获取微信公众号的access_token

        static public string access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
        static public string GetAccessToken(string appid, string appsecret)
        {
            string requestUrl = access_token_url.Replace("APPID", appid).Replace("APPSECRET", appsecret);
            WebResponse result = null;
            WebRequest req = WebRequest.Create(requestUrl);
            result = req.GetResponse();
            Stream s = result.GetResponseStream();
            XmlDictionaryReader xmlReader = JsonReaderWriterFactory.CreateJsonReader(s, XmlDictionaryReaderQuotas.Max);
            xmlReader.Read();
            string xml = xmlReader.ReadOuterXml();
            s.Close();
            s.Dispose();

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);
            XmlElement rootElement = doc.DocumentElement;
            string access_token = rootElement.SelectSingleNode("access_token").InnerText.Trim();
            return access_token;
        }

猜你喜欢

转载自www.cnblogs.com/hofmann/p/12342340.html