繁体   English   中英

使用Windows Phone 8.1的C#获取访问令牌

[英]Get Access Token Using C#, Windows phone 8.1

我正在尝试获取供稿的访问令牌。下面是一个代码,我曾经获取访问令牌。

public async Task<string> GetAccessToken()
        {
            string postString = String.Format("username={0}&password={1}&grant_type=password", "userName", "pwd");

            string url = "http://example.net/Token";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.ToString());
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            UTF8Encoding utfenc = new UTF8Encoding();
            byte[] bytes = utfenc.GetBytes(postString);


            try
            {
                HttpWebResponse webResponse = (HttpWebResponse)(await request.GetResponseAsync());
                Stream responseStream = webResponse.GetResponseStream();
                StreamReader responseStreamReader = new StreamReader(responseStream);
                string result = responseStreamReader.ReadToEnd();//parse token from result
            }
            catch(Exception ex)
            {
            }
            return "";
        }

下面的错误

"An error occurred while sending the request. The text associated with this error code could not be found.

The server name or address could not be resolved"

执行以下代码时抛出

HttpWebResponse webResponse = (HttpWebResponse)(await request.GetResponseAsync());

请帮我解决问题

如果您正在使用POST请求,请尝试此操作

public async Task<string> GetAccessToken()
    {
        string postString = String.Format("username={0}&password={1}&grant_type=password", "userName", "pwd");
        try
        {
            using (var httpClient = new HttpClient())
            {
                var request1 = new HttpRequestMessage(HttpMethod.Post, "FeedURL");
                request1.Content = new StringContent(postString);
                var response = await httpClient.SendAsync(request1);
                var result1 = await response.Content.ReadAsStringAsync();
                result1 = Regex.Replace(result1, "<[^>]+>", string.Empty);
                var rootObject1 = JObject.Parse(result1);
                string accessToken = rootObject1["access_token"].ToString();
            }

        }
        catch (Exception ex)
        {

        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM