2017-04-22 66 views
1

我正在研究連接到抽搐登錄。當我在他們的文檔看看如何設置它,這就是它說:如何正確調用post方法來抽動api?

POST https://api.twitch.tv/kraken/oauth2/token 

POST Body (URL-encoded) 
client_id=<your client ID> 
&client_secret=<your client secret> 
&grant_type=authorization_code 
&redirect_uri=<your registered redirect URI> 
&code=<authorization code received above> 
&state=<your unique token generated by your application> 

https://dev.twitch.tv/docs/v5/guides/authentication/#implicit-grant-flow (我下面的「授權碼流」指南)。

但是,我目前有一些問題,使其工作。這是我的代碼如下所示:

static public async Task getTwitchData() 
    { 
     var httpClientRequest = new HttpClient(); 

     var postData = new Dictionary<string, object>(); 
     postData.Add("client_id", clientId); 
     postData.Add("client_secret", secretId); 
     postData.Add("grant_type", accesstoken); 
     postData.Add("redirect_uri", redirectURL); 
     postData.Add("code", accesstoken); 
     postData.Add("state", mycreatedtoken); 

     var jsonRequest = JsonConvert.SerializeObject(postData); 
     HttpContent content = new StringContent(jsonRequest, System.Text.Encoding.UTF8, "application/json"); 

     var result = await httpClientRequest.PostAsync("https://api.twitch.tv/kraken/oauth2/token", content); 
     try 
     { 
      var resultString = await result.Content.ReadAsStringAsync(); 
      var jsonResult = JObject.Parse(resultString); 
      System.Diagnostics.Debug.WriteLine(jsonResult); 
      return jsonResult; 
     } 

     catch 
     { 
      System.Diagnostics.Debug.WriteLine(result); 
      return null; 
     } 
    } 

如果我運行這個功能它沒有達到「嘗試」,因爲它無法找到JSON。相反,它到達那裏這會打印出「抓」:

StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: 

,什麼我應該得到(如果做得正確)是JSON看起來像這樣的迴應:

{ 
"access_token": "<user access token>", 
"scope": <your previously listed scope(s)> 
} 
+0

您是否通過https發送了您的請求? – aaronw

+0

是的我使用'Microsoft.Net.Http'框架。在代碼的開始部分,您可以看到我如何使用它:'var httpClientRequest = new HttpClient();' – TokyoCode

+0

您是否在調試模式下啓用了ssl? httpclient類將使用您設置應用程序使用的任何協議。我問,因爲大多數oauth2實現會強制你使用https,雖然他們應該告訴你,在你返回的錯誤信息,而不是給你一個400 ... – aaronw

回答

0

使用隱式授權流程如果您的應用程序不是使用服務器,如客戶端JavaScript應用程序或移動應用程序。這種方法不需要必須向API發出請求的服務器。

如果您從移動應用發出這些請求,則應該使用Implicit Grant Flow而不是Authorization Code Flow

授權碼流程用於從您的服務器訪問Twitch,而不是移動應用程序。

回覆:https://dev.twitch.tv/docs/v5/guides/authentication/