为 facebook 请求 Access_Token 时出现 400 bad request 错误

发布于 2024-10-29 15:40:29 字数 3521 浏览 1 评论 0原文

我在向 facebook 请求访问令牌时遇到一些问题。首先它起作用了。但现在它不再起作用了,我不认为我改变了特定代码行中的某些内容。

这是我一直在做的事情:

public static String requestAccesToken(string code)
    {
        //create the constructor with post type and few data
        MyWebRequest myRequest = new MyWebRequest("https://graph.facebook.com/oauth/access_token?", "POST", "client_id=" + getAppID() + "&client_secret=" + getAppSecret() + "&code=" + code + "&redirect_uri=http://localhost:57689/search.aspx");

        string accessToken = myRequest.GetResponse().Split('&')[0];  
        accessToken = accessToken.Split('=')[1];

        return accessToken;
    }
 public static String getAppID()
    {
        return System.Configuration.ConfigurationManager.AppSettings["AppID"].ToString();
    }

    public static String getAppSecret()
    {
        return System.Configuration.ConfigurationManager.AppSettings["AppSecret"].ToString();
    }

类:MyWebrequest:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.IO;
using System.Text;

public class MyWebRequest
{
    private WebRequest request;
    private Stream dataStream;

    private string status;

    public String Status
    {
        get
        {
            return status;
        }
        set
        {
            status = value;
        }
    }
    /*
     * simply download the data of the web page
     */
    public MyWebRequest(string url)
    {
        // Create a request using a URL that can receive a post.

        request = WebRequest.Create(url);
    }

    public MyWebRequest(string url, string method)
        : this(url)
    {

        if (method.Equals("GET") || method.Equals("POST"))
        {
            // Set the Method property of the request to POST.
            request.Method = method;
        }
        else
        {
            throw new Exception("Invalid Method Type");
        }
    }

    public MyWebRequest(string url, string method, string data)
        : this(url, method)
    {

        // Create POST data and convert it to a byte array.
        string postData = data;
        byte[] byteArray = Encoding.UTF8.GetBytes(postData);

        // Set the ContentType property of the WebRequest.
        request.ContentType = "application/x-www-form-urlencoded";

        // Set the ContentLength property of the WebRequest.
        request.ContentLength = byteArray.Length;

        // Get the request stream.
        dataStream = request.GetRequestStream();

        // Write the data to the request stream.
        dataStream.Write(byteArray, 0, byteArray.Length);

        // Close the Stream object.
        dataStream.Close();

    }

    public string GetResponse()
    {
        // Get the original response.
        WebResponse response = request.GetResponse(); //400 ERROR BAD REQUEST

        this.Status = ((HttpWebResponse)response).StatusDescription;

        // Get the stream containing all content returned by the requested server.
        dataStream = response.GetResponseStream();

        // Open the stream using a StreamReader for easy access.
        StreamReader reader = new StreamReader(dataStream);

        // Read the content fully up to the end.
        string responseFromServer = reader.ReadToEnd();

        // Clean up the streams.
        reader.Close();
        dataStream.Close();
        response.Close();

        return responseFromServer;
    }

}

哪里出了问题?我真的被这个困住了。

感谢您的阅读!

I've some problems with requesting an access token from facebook. First it worked. But now it doesn't work anymore and i don't think that i changed something in the specific codelines.

Here's how i've been doing it:

public static String requestAccesToken(string code)
    {
        //create the constructor with post type and few data
        MyWebRequest myRequest = new MyWebRequest("https://graph.facebook.com/oauth/access_token?", "POST", "client_id=" + getAppID() + "&client_secret=" + getAppSecret() + "&code=" + code + "&redirect_uri=http://localhost:57689/search.aspx");

        string accessToken = myRequest.GetResponse().Split('&')[0];  
        accessToken = accessToken.Split('=')[1];

        return accessToken;
    }
 public static String getAppID()
    {
        return System.Configuration.ConfigurationManager.AppSettings["AppID"].ToString();
    }

    public static String getAppSecret()
    {
        return System.Configuration.ConfigurationManager.AppSettings["AppSecret"].ToString();
    }

Class: MyWebrequest:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.IO;
using System.Text;

public class MyWebRequest
{
    private WebRequest request;
    private Stream dataStream;

    private string status;

    public String Status
    {
        get
        {
            return status;
        }
        set
        {
            status = value;
        }
    }
    /*
     * simply download the data of the web page
     */
    public MyWebRequest(string url)
    {
        // Create a request using a URL that can receive a post.

        request = WebRequest.Create(url);
    }

    public MyWebRequest(string url, string method)
        : this(url)
    {

        if (method.Equals("GET") || method.Equals("POST"))
        {
            // Set the Method property of the request to POST.
            request.Method = method;
        }
        else
        {
            throw new Exception("Invalid Method Type");
        }
    }

    public MyWebRequest(string url, string method, string data)
        : this(url, method)
    {

        // Create POST data and convert it to a byte array.
        string postData = data;
        byte[] byteArray = Encoding.UTF8.GetBytes(postData);

        // Set the ContentType property of the WebRequest.
        request.ContentType = "application/x-www-form-urlencoded";

        // Set the ContentLength property of the WebRequest.
        request.ContentLength = byteArray.Length;

        // Get the request stream.
        dataStream = request.GetRequestStream();

        // Write the data to the request stream.
        dataStream.Write(byteArray, 0, byteArray.Length);

        // Close the Stream object.
        dataStream.Close();

    }

    public string GetResponse()
    {
        // Get the original response.
        WebResponse response = request.GetResponse(); //400 ERROR BAD REQUEST

        this.Status = ((HttpWebResponse)response).StatusDescription;

        // Get the stream containing all content returned by the requested server.
        dataStream = response.GetResponseStream();

        // Open the stream using a StreamReader for easy access.
        StreamReader reader = new StreamReader(dataStream);

        // Read the content fully up to the end.
        string responseFromServer = reader.ReadToEnd();

        // Clean up the streams.
        reader.Close();
        dataStream.Close();
        response.Close();

        return responseFromServer;
    }

}

Where is this going wrong? I'm realy stuck with this one.

Thank you for reading!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

没有伤那来痛 2024-11-05 15:40:29

我昨天也遇到了同样的问题。我使用 WebClient 而不是 WebRequest 修复了它。我认为出现 Http 错误 是因为响应使用 gzip 编码 并且因为我在 redirect_uri 中发送了一些参数(我不确定如果这是原因,但它现在正在工作):

            try
            {
                WebClient wc = new WebClient();

                wc.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip");

                //that solves the problem with GZIP partially:
                wc.Proxy = null;

                using (StreamReader reader = new StreamReader(wc.OpenRead(url)))
                {
                    string conteudo = reader.ReadToEnd();

                    ...

I had the same problem yesterday. I fixed it using WebClient instead of WebRequest. I think the Http error was appearing because the response was using gzip encode and because I was sending some parameters in the redirect_uri (I am not sure if that was the reason, but it is working now):

            try
            {
                WebClient wc = new WebClient();

                wc.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip");

                //that solves the problem with GZIP partially:
                wc.Proxy = null;

                using (StreamReader reader = new StreamReader(wc.OpenRead(url)))
                {
                    string conteudo = reader.ReadToEnd();

                    ...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文