Imgur API 上传

2024-03-02

于是就有了这行代码

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

当我注册 Imgur API 时,我得到了一个 client_id 和一个 client_secret,并且想知道我使用哪一个来表示“您的 API 密钥在这里”,也在第二行的第一部分中表示“密钥”是什么我要进入那里吗?还有就是上传的网站http://imgur.com/api/upload http://imgur.com/api/upload因为我见过一些不同的。


试试这个:

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

几乎就像矮胖子一样,将每一部分重新组合在一起,来自各地的代码,至少它按预期工作,遗憾的是他们没有示例......
enjoy.

ps:ou也可以使用FILES(还没有尝试过),但你需要将图像转换为base64,然后转换为utf8(以替换url)

编辑,使用它而不是 URL,以便您可以上传文件:

  //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");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Imgur API 上传 的相关文章

随机推荐