Uploading Image To Imgur

1.1k views Asked by At

I want to upload an image from my harddrive to imgur and return the direct link to it so that the image can be added to forum posts inside image tags or whatever.

I already registered on imgur and got a client id for my application. I tried various code examples on stackoverflow but none worked. Please help me to get working code for this. See below for the ones I tried.

// Stuck after "Connecting..."
public static void upload(BufferedImage image)
{
    String IMGUR_POST_URI = "https://api.imgur.com/3/upload";
    String IMGUR_API_KEY = CLIENT_ID;

    try
    {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        System.out.println("Writing image...");
        ImageIO.write(image, "png", baos);
        URL url = new URL(IMGUR_POST_URI);

        System.out.println("Encoding...");
        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...");
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Authorization", "Client-ID "
                + IMGUR_API_KEY);
        conn.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");

        OutputStreamWriter wr = new OutputStreamWriter(
                conn.getOutputStream());

        System.out.println("Sending data...");
        wr.write(data);
        wr.flush();

        System.out.println("Finished.");

        // just display the raw response
        BufferedReader in = new BufferedReader(new InputStreamReader(
                conn.getInputStream()));
        String line;
        while ((line = in.readLine()) != null)
        {
            System.out.println(line);
        }
        in.close();

    } catch (Exception e)
    {
        System.out.println("Error: " + e.getMessage());
        e.printStackTrace();
    }
}

Another example:

    // Exception in thread "main" java.io.IOException: Server returned HTTP response code: 400 for URL: https://api.imgur.com/3/image
    public static String getImgurContent(String imageDir, String clientID)
        throws Exception
{
    URL url;
    url = new URL("https://api.imgur.com/3/image");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    String data = URLEncoder.encode("image", "UTF-8") + "="
            + URLEncoder.encode(imageDir, "UTF-8");

    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Authorization", "Client-ID " + clientID);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type",
            "application/x-www-form-urlencoded");

    conn.connect();
    StringBuilder stb = new StringBuilder();
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();

    // Get the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(
            conn.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null)
    {
        stb.append(line).append("\n");
    }
    wr.close();
    rd.close();

    return stb.toString();
}

And finally:

// null : null
public static String Imgur(String imageDir, String clientID)
{
    // create needed strings
    String address = "https://api.imgur.com/3/image";

    // Create HTTPClient and post
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(address);

    // create base64 image
    BufferedImage image = null;
    File file = new File(imageDir);

    try
    {
        // read image
        image = ImageIO.read(file);
        ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
        ImageIO.write(image, "png", byteArray);
        byte[] byteImage = byteArray.toByteArray();
        String dataImage = new Base64().encodeAsString(byteImage);

        // add header
        post.addHeader("Authorization", "Client-ID " + clientID);
        // add image
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("image", dataImage));
        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // execute
        HttpResponse response = client.execute(post);

        // read response
        BufferedReader rd = new BufferedReader(new InputStreamReader(
                response.getEntity().getContent()));
        String all = null;

        // loop through response
        while (rd.readLine() != null)
        {
            all = all + " : " + rd.readLine();
        }

        return all;

    } catch (Exception e)
    {
        return "error: " + e.toString();
    }
}
0

There are 0 answers