从重定向的URL获取访问令牌的简单方法

时间:2014-02-08 15:00:59

标签: c# httpwebrequest access-token

我必须在C#中使用HttpWebRequest来检索访问令牌。

我的基本网址会将我重定向到另一个包含访问令牌的网址。

有没有办法用它来获取访问令牌?

这是我在应用答案建议后的代码:

 // Create a request for the URL. 
            string url = "https://stackexchange.com/oauth/dialog?client_id=2532&scope=no_expiry&redirect_uri=https://stackexchange.com/oauth/login_success"; 
            WebRequest request = WebRequest.Create(
              url);
            request.Method = "GET";
            // If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials;
            // Get the response.
            WebResponse response = request.GetResponse();
            // Display the status.
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Display the content.
            Console.WriteLine(responseFromServer);
            // Clean up the streams and the response.
            reader.Close();
            response.Close();

调试中断行:WebResponse response = request.GetResponse(); VS告诉我服务器有一般错误:500。 如果我尝试使用https://www.google.com,则无错误。

1 个答案:

答案 0 :(得分:2)

您可以从ResponseUri属性中获取生成的网址。

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
    NaveValueCollection urlParameters = HttpUtility.ParseQueryString(response.ResponseUri.Query);

    // extract the access token from the url.

    string accessToken = urlParameters["access_token"];
}