Imgur API uploading

家住魔仙堡 提交于 2019-12-06 04:29:50

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");
Karl Green

The site to upload to is - https://api.imgur.com/3/image or you can alternatively use the same link with "upload" instead of image.

I am currently trying to use the Imgur API myself and although I have not got it completely right yet (I can't seem to parse the URL response) I have looked at quite a few code examples for it. Are you definitely using version 3 of the API?

Because the homepage of the API says that you should give your client ID in this format "Authorization Client-ID YOUR_CLIENT_ID", not using "key" like you are.

Have a look at http://api.imgur.com/

Edit: you might find the following useful - Anonymous Uploading File object to Imgur API (JSON) gives Authentication Error 401

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!