簡體   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