Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Imgur API uploading

Tags:

java

imgur

So there is this line of code

String data = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode(Base64.encodeBase64String(baos.toByteArray()).toString(), "UTF-8");

data += "&" + URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode(YOUR API KEY GOES HERE, "UTF-8");

and when I registered for the Imgur API I was given a client_id and a client_secret and was wondering which one I use for where it says "YOUR API KEY GOES HERE" also in the first part in the second line where it says "key" what do I enter there? Also is the site to upload it http://imgur.com/api/upload because I have seen a few different ones.

like image 611
user2526311 Avatar asked Jun 30 '26 22:06

user2526311


1 Answers

try this out:

    public static String getImgurContent(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(IMAGE_URL, "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();
}

was almost like humpty dumpty, getting every piece back together, codes from everywhere, at least it worked as expected, its a shame they don't have examples...
enjoy.

ps: ou can also make with FILES (haven't tried yet) but you need to convert an image to base64 and then to utf8 (to replace the url)

edit, use this instead of the URL, so you can upload files:

  //create base64 image
    BufferedImage image = null;
    File file = new File(imageDir);
    //read image
    image = ImageIO.read(file);
    ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
    ImageIO.write(image, "png", byteArray);
    byte[] byteImage = byteArray.toByteArray();
    String dataImage = Base64.encode(byteImage);
    String data = URLEncoder.encode("image", "UTF-8") + "="
    + URLEncoder.encode(dataImage, "UTF-8");
like image 125
Simego Avatar answered Jul 02 '26 11:07

Simego