Imgur OAuth2:如何为访问令牌交换授权码

Imgur OAuth2: How to exchange autorization code for an access token

我正在尝试创建一个在 Imgur 上上传的 c# 网络应用程序。目前我刚刚成功获得 authorization_code,但每次我尝试获得访问令牌时,我都会收到错误 "Missing required fields"。正如 API Docs 中所写,我提出 POST 请求:

https://api.imgur.com/oauth2/token?client_id=MY_CLIENT_ID&client_secret=MY_CLIENT_SECRET&grant_type=authorization_code&code=CODE

其中:

也许我遗漏了一些小细节,但这就是 API 文档所说的。

我有同样的问题实际上问题是我使用 x-www-form-urlencoded 将参数发送到 URL(就像你做的一样,它似乎被 imgur API 团队禁止可以是一些安全问题)所以你需要使用表单数据。但我没有在 api 文档中找到它。下面我分享C#的代码示例

using System.IO;
using System;
using System.Net;
using System.Text;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

class Program
{
    static void Main()
    {
        sendRequest("https://api.imgur.com/oauth2/token");
    }

    private static void sendRequest(String url){

        using(WebClient client = new WebClient())
        {
            System.Collections.Specialized.NameValueCollection reqparm = new System.Collections.Specialized.NameValueCollection();
            reqparm.Add("client_id", "Your client_id");
            reqparm.Add("client_secret", "Your client_secret");
            reqparm.Add("grant_type", "authorization_code");
            reqparm.Add("code", "your returned code");

            ServicePointManager.ServerCertificateValidationCallback = 
                delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) 
                    { return true; };
            System.Net.ServicePointManager.Expect100Continue = false;
            byte[] responsebytes = client.UploadValues(url, "POST", reqparm);
            string responsebody = Encoding.UTF8.GetString(responsebytes);
            Console.WriteLine(responsebody);
        }
    }
 }