简体   繁体   中英

Get Access Token Using C#, Windows phone 8.1

I am trying to get the access token for the feed.Below is a code, i used to get the access token.

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 "";
        }

The error below

"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"

is throwing while it executes the below code

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

Please help me to solve the issue

Try this if you are using POST request

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)
        {

        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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