Ahm*_*mad 4 c# post httpresponse image-uploading imgur
我正在尝试将此功能添加到我正在开发的C#Windows应用程序中,以便将图像上传到Imgur.
不幸的是,它必须是Imgur,因为该网站是必需的.
问题是,我能找到的C#示例代码是旧的,似乎不适用于他们的版本3 API.
所以我想知道在该领域有专长的人是否可以帮助我.
我更愿意使用OAuth上传,而不是匿名选项,但如果需要,后者可以用作示例.
编辑:
一部分我特别不明白的是我怎么能做出,而其余的授权步骤发生中的桌面应用程序.授权步骤需要打开网页,询问用户是否允许应用程序使用其数据.
如何为基于桌面的应用程序执行此操作?
在开始之前,您需要注册您的应用程序以接收客户端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; }
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3815 次 |
最近记录: |