2014-05-14 50 views
1

我正在嘗試創建圖片上傳模塊使用Imgur API 我剛註冊後得到了客戶端ID和客戶端密碼。當涉及到實現和測試,它失敗並給出了logcat的上傳失敗後檢索圖片鏈接

   {"data":{"error":"We're really sorry, but 
     anonymous uploading in your country has 
been disabled. Please <a href=\"\/register\">register 
     for an account<\/a> and try uploading again.","request":"\/3\/upload.json","method":"POST"} 
    ,"success":false,"status":400} 

在下面的logcat的響應如下回應是我的代碼

public String uploadToImgur(File uploadFile) { 
     DefaultHttpClient defaulthttpclient; 
     HttpPost httppost; 
     MultipartEntity multipartentity; 
     String path = uploadFile.getAbsolutePath().toString(); 
     String s; 
     defaulthttpclient = new DefaultHttpClient(); 

     String targetURL = "https://api.imgur.com/3/upload.json"; 
     String apikey = "client_secret"; 
     httppost = new HttpPost(targetURL); 

     httppost.setHeader("User-Agent", USER_AGENT); 
     httppost.addHeader("Authorization", "Client-ID {client)_id}"); 
     multipartentity = new MultipartEntity(); 
     s = path.substring(1 + path.lastIndexOf(".")); 
     if (s.lastIndexOf("jpg") >= 0) 
     { 
      s = "jpeg"; 
     } 
     try 
     { 
      multipartentity.addPart("image", new FileBody(new File(path), (new StringBuilder("image/")).append(s).toString())); 
      multipartentity.addPart("key", new StringBody(apikey)); 
      httppost.setEntity(multipartentity); 
      String s1 = EntityUtils.toString(defaulthttpclient.execute(httppost).getEntity()); 
      Log.d("outpur" , s1); 
      if (s1.lastIndexOf("<original>") >= 0 && s1.indexOf("</original>") >= 0) 
      { 
       return (new StringBuilder("[img]")).append(s1.substring(10 + s1.lastIndexOf("<original>"), s1.indexOf("</original>"))).append("[/img]").toString(); 
      } 
     } 
     catch (Exception exception) 
     { 
      return "ERRor"; 
     } 
     return "Error"; 
    } 

請你告訴我有什麼更好的方法來增強上傳模塊?

回答

0

註冊和發送客戶端ID是不夠好的非匿名上傳。該文檔告訴您使用oAuth並獲取需要傳遞的令牌以滿足此類請求。

身份驗證 該API要求每個客戶端使用OAuth 2身份驗證。這意味着您必須註冊您的應用程序,並且如果您想以用戶身份登錄,請生成access_code。 對於公共只讀和匿名資源,例如獲取圖像信息,查找用戶註釋等,您只需在請求中發送帶有您的client_id的授權標頭。如果您想匿名上傳圖片(沒有圖片與帳戶綁定),或者您想創建匿名相冊,這也適用。這讓我們知道哪個應用程序正在訪問API。 授權:客戶ID YOUR_CLIENT_ID 用於訪問用戶的帳戶,請訪問文檔

+0

我不要的部分的OAuth2;不懂...這是我必須去使用什麼樣的代碼,以便在API? –

+0

請查看https://api.imgur.com/oauth2這個文檔,它解釋了imgur如何遵循標準的oAuth協議。至少從您收到的文檔和郵件中,很明顯您需要獲取訪問令牌才能進行非匿名上傳。 – Raghu