2013-04-23 72 views
4

我試圖將這個功能添加到我在開發中的C#Windows應用程序,以將圖像上傳到Imgur。Imgur API版本3上傳示例?

不幸的是它必須是Imgur,因爲該網站是要求。

問題是,無論我能找到的C#示例代碼是舊的,似乎都不適用於它們的版本3 API。

所以我想知道是否有人在該領域的專業知識可以幫助我。

我寧願上傳使用OAuth,而不使用匿名選項,但後者可以作爲一個例子,如果需要的話。

編輯:

一個部分我特別不明白的是我怎麼能做出,而內桌面應用程序其餘授權步驟發生。授權步驟需要打開網頁,在網頁中詢問用戶是否允許應用程序使用他們的數據。

如何爲基於桌面的應用程序執行此操作?

+0

我的應用程序目前使用Imgur API 2.0,我也對一些例子感興趣! – 2013-04-23 20:16:18

+0

你希望如何上傳?外部URL,base64編碼的圖像內容或分段上傳? – flup 2013-05-03 18:28:48

+0

@flup我不知道OP。但是base64在這裏。 – 2013-05-05 18:14:00

回答

6

在開始之前,您需要註冊您的應用程序以接收clientID和客戶端密鑰。猜猜你已經知道了。詳細信息可在官方Imgur API Documentation找到。

關於身份驗證你是正確的,用戶必須訪問一個網頁,並抓住並授權你的appication那裏。您可以在您的應用程序中嵌入一些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; } 
    } 
+3

您是否還可以包含一個爲賞金上傳位圖的示例 – 2013-04-30 20:49:52