在开始之前,您需要注册您的应用程序以接收客户端 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; }
}