Search code examples
javauploadhyperlinkimgur

Retrieving imgur upload link after uploading an image through java


So I am using one of the imgur api examples for uploading an image but am stuck on how I retrieve the upload link to view the image.

This is what I have so far, and from what I can tell it uploads it but that itself is not very useful without getting a link to the upload.

This is what I have thus far.

    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();}

Solution

  • You should get back either an xml or json with the 'response' to the upload, according to the imgur docs.

    I found this little snippet of code that is an example of getting the response after writing to a URL connection, maybe it will help you. This isn't specific to imgur but I think the code should be similar.

    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();
    }