将文件发送到 Java 中的 API

Send a file to a API in Java

我正在使用创建 QR 并将其发送到 API 的库 QRCodeWriter。

问题是我有存储图像的变量 os,但我无法将它添加到 MultipartEntity 以发送它(注释行) .

错误是:类型不兼容:无法将 ByteArrayOutputStream 转换为 ContentBody entity.addPart("file", os)

我试了很多代码转换图片都没有成功。

我们将不胜感激

    String url =  "https://apiURL.com";
    String accessToken = "123456789";

    QRCodeWriter writer = new QRCodeWriter();
    BitMatrix matrix = writer.encode("https://www.google.com/", BarcodeFormat.QR_CODE, 350, 350);
    BufferedImage image = MatrixToImageWriter.toBufferedImage(matrix);

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    ImageIO.setUseCache(false);
    ImageIO.write(image,"png",os);
    
    context.log(os.toString());
    basicIO.write("TestData");

    MultipartEntity entity = new MultipartEntity();
    //entity.addPart("file", os);

    HttpResponse returnResponse = Request.Post(url).addHeader("Authorization", accessToken).body(entity).execute().returnResponse();
    context.log("Response status: " + returnResponse.getStatusLine().getStatusCode());
    context.log(EntityUtils.toString(returnResponse.getEntity()));
    

有效改变:

entity.addPart("file", os);

至:

entity.addPart("file", new ByteArrayBody(os.toByteArray(), "qr.png"));