如何正确调用post方法来抽动api?

问题描述:

我正在研究连接到抽搐登录。当我在他们的文档看看如何设置它,这就是它说:如何正确调用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

使用隐式授权流程如果您的应用程序不是使用服务器,如客户端JavaScript应用程序或移动应用程序。这种方法不需要必须向API发出请求的服务器。

如果您从移动应用发出这些请求,则应该使用Implicit Grant Flow而不是Authorization Code Flow

授权码流程用于从您的服务器访问Twitch,而不是移动应用程序。

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