Anbarasi
Anbarasi

Reputation: 421

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

Upvotes: 0

Views: 138

Answers (1)

Vishnu Babu
Vishnu Babu

Reputation: 1275

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

        }
    }

Upvotes: 1

Related Questions