2012-04-24 244 views
2

因此,我正在使用imgur api示例之一上傳圖片,但我堅持如何檢索上傳鏈接以查看圖片。在通過java上傳圖片後檢索imgur上傳鏈接

這是我迄今爲止,從我可以告訴它上傳它,但它本身沒有得到一個鏈接到上傳不是很有用。

這是我到目前爲止。

String IMGUR_POST_URI = "http://api.imgur.com/2/upload.xml"; 
    String IMGUR_API_KEY = "MY API KEY"; 

    String file = "C:\\Users\\Shane\\Pictures\\Misc\\001.JPG"; 
    try 
    { 
     // Creates Byte Array from picture 
     ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
     System.out.println("Writing image..."); 
     ImageIO.write(getBufferedImageFromImage(Toolkit.getDefaultToolkit().createImage(file)), "png", baos); 
     URL url = new URL(IMGUR_POST_URI); 
     System.out.println("Encoding..."); 
     //encodes picture with Base64 and inserts api key 
     String data = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode(Base64.encodeBase64String(baos.toByteArray()).toString(), "UTF-8"); 
     data += "&" + URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode(IMGUR_API_KEY, "UTF-8"); 
     System.out.println("Connecting..."); 
     // opens connection and sends data 
     URLConnection conn = url.openConnection(); 
     conn.setDoOutput(true); 
     OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 
     System.out.println("Sending data..."); 
     wr.write(data); 
     wr.flush(); 
    } 
    catch(Exception e){e.printStackTrace();} 

回答

1

根據imgur文檔,您應該找回帶有對上傳的「響應」的xml或json。

我發現了這個小代碼片段,它是在寫入URL連接之後獲取響應的示例,也許它會對您有所幫助。這不是特定於imgur,但我認爲代碼應該類似。

public static void main(String[] args) throws Exception { 

    String stringToReverse = URLEncoder.encode(args[1], "UTF-8"); 

    URL url = new URL(args[0]); 
    URLConnection connection = url.openConnection(); 
    connection.setDoOutput(true); 

    OutputStreamWriter out = new OutputStreamWriter(
            connection.getOutputStream()); 
    out.write("string=" + stringToReverse); 
    out.close(); 

    BufferedReader in = new BufferedReader(
           new InputStreamReader(
           connection.getInputStream())); 
    String decodedString; 
    while ((decodedString = in.readLine()) != null) { 
     System.out.println(decodedString); 
    } 
    in.close(); 
} 
+0

Thanks!這解決了它!現在做一些有趣的舊正則表達式建設。 – ShaneIsrael 2012-04-24 23:37:42