有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Imgur API上传

这是一行代码

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时,我得到了一个客户id和一个客户机密,我想知道我使用哪一个,它在第二行的第一部分写着“你的API密钥在这里”,它在第二行的第一部分写着“密钥”,我在那里输入什么?也是上传它的网站http://imgur.com/api/upload,因为我看到了一些不同的网站


共 (1) 个答案

  1. # 1 楼答案

    试试这个:

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

    就像humpty dumpty一样,把每一块都重新组装起来,到处都是代码,至少它像预期的那样工作,很遗憾他们没有例子
    享受吧

    ps:你也可以使用文件制作(还没有尝试过),但你需要将图像转换为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");