1

我正在使用以下代碼向Facebook圖形api oauth服務器發送獲取請求。在C#中使用GetResponseStream()獲取'(400)Bad Request'

public string GetAccessToken(string code) 
    { 
     HttpWebRequest req = (HttpWebRequest) WebRequest.Create(@"https://graph.facebook.com/oauth/access_token?client_id=249725835046216&redirect_uri=http://localhost:2794/&client_secret=APP_SECRETa&code=" + code); 
     HttpWebResponse res = (HttpWebResponse)req.GetResponse(); 
     string response=res.GetResponseStream().ToString(); 
     return response; 
    } 

上面的代碼會引發以下異常:

The remote server returned an error: (400) Bad Request. 

同時,如果我在瀏覽器中輸入相同的URL,它的工作原理。請幫忙,我錯在哪裏?

(PS在URL中,我肯定用密鑰更換APP_SECRET)

回答

0

最可能的是,你需要指定用戶代理,以滿足服務器的一些檢查電路:

HttpWebRequest req = (HttpWebRequest) WebRequest.Create(@"https://...&code=" + code); 
req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; 

試試這個並看看它是否有幫助。

2

你的查詢字符串參數應url編碼:

HttpWebRequest req = (HttpWebRequest) WebRequest.Create(@"https://graph.facebook.com/oauth/access_token?client_id=249725835046216&redirect_uri=" + UrlEncode("http://localhost:2794/") + "&client_secret=" + UrlEncode(APP_SECRET) + "&code=" + UrlEncode(code)); 
1

你必須編碼您的URL的參數。您可以使用HttpUtility類 來編碼您的參數。

0

這就是發生在我身上,如何解決:

  1. 將用戶重定向到

    https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID&redirect_uri=YOUR_URL

  2. 後用戶點擊允許,它會打我們的重定向Uri

  3. 在這一點上,我們會得到公司德,我們需要在服務器端 HTTP GET做以下網址與我們的OAuth 接入令牌交換代碼:

    https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&client_secret=YOUR_APP_SECRET&code=THE_CODE_FROM_ABOVE

現在,在步驟3中,我一直在得到HTTP 400迴應。

因此經過一番調查後,我發現在step 3上我們提交的redirect_uri沒有做任何事情,只是驗證了請求。因此,值需要進行步驟2。

匹配簡而言之:

REDIRECT_URI必須同時匹配step 2step 3

相關問題