4

我正在尝试将此功能添加到我正在开发的 C# Windows 应用程序中,用于将图像上传到 Imgur。

不幸的是,它必须是 Imgur,因为该站点是必需的。

问题是我能找到的任何 C# 示例代码都是旧的,并且似乎不适用于他们的版本 3 API。

所以我想知道是否有该领域的专业人士可以帮助我。

我更喜欢使用 OAuth 上传,而不是匿名选项,但如果需要,后者可以用作示例。

编辑:

我特别不明白的一部分是如何在保留桌面应用程序中的同时进行授权步骤。授权步骤需要打开一个网页,询问用户是否允许应用程序使用他们的数据。

如何为基于桌面的应用程序执行此操作?

4

1 回答 1

7

在开始之前,您需要注册您的应用程序以接收客户端 ID 和客户端密码。猜猜你已经意识到了。详细信息可以在官方Imgur API 文档中找到。

关于身份验证,您是对的,用户必须访问网页并在那里获取并授权您的应用程序。您可以在应用程序中嵌入一些 Webbrowser 控件,也可以简单地指示用户浏览网页。

这是一些未经测试的代码,只需稍加修改即可使用。

class Program
    {
        const string ClientId = "abcdef123";
        const string ClientSecret = "Secret";

        static void Main(string[] args)
        {
            string Pin = GetPin(ClientId, ClientSecret);
            string Tokens = GetToken(ClientId, ClientSecret, Pin);

            // Updoad Images or whatever :)
        }

        public static string GetPin(string clientId, string clientSecret)
        {
            string OAuthUrlTemplate = "https://api.imgur.com/oauth2/authorize?client_id={0}&response_type={1}&state={2}";
            string RequestUrl = String.Format(OAuthUrlTemplate, clientId, "pin", "whatever");
            string Pin = String.Empty;

            // Promt the user to browse to that URL or show the Webpage in your application
            // ... 

            return Pin;
        }

        public static ImgurToken GetToken(string clientId, string clientSecret, string pin)
        {
            string Url = "https://api.imgur.com/oauth2/token/";
            string DataTemplate = "client_id={0}&client_secret={1}&grant_type=pin&pin={2}";
            string Data = String.Format(DataTemplate, clientId, clientSecret, pin);

            using(WebClient Client = new WebClient())
            {
                string ApiResponse = Client.UploadString(Url, Data);

                // Use some random JSON Parser, you´ll get access_token and refresh_token
                var Deserializer = new JavaScriptSerializer();
                var Response = Deserializer.DeserializeObject(ApiResponse) as Dictionary<string, object>;

                return new ImgurToken()
                {
                    AccessToken = Convert.ToString(Response["access_token"]),
                    RefreshToken = Convert.ToString(Response["refresh_token"])
                };
            }
        }
    }

    public class ImgurToken
    {
        public string AccessToken { get; set; }
        public string RefreshToken { get; set; }
    }
于 2013-04-30T18:39:36.637 回答