首页 > 解决方案 > 在 Java 中通过 http 请求发送 base64 图像会丢失一些字符

问题描述

我一直在尝试使用 API 发送 base64 图像javaNodeJS经过几个小时的工作和搜索,我不知道是什么可能导致以下问题,问题如下:

在nodejs中记录base64图像后,我看到所有+字符都替换为space

这是原始base64的一部分Java

f8A0NH2qH+/+hooouAfaof7/wCho+1Q/

这是接收到的图像的一部分NodeJS

f8A0NH2qH / hooouAfaof7/wCho 1Q/

我试图通过发送图像POSTMAN,完全没有问题。

所有步骤如下:

1-我正在使用以下代码段将图像转换为 base64

public static String imgToBase64String(final RenderedImage img, final String formatName) {
        final ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ImageIO.write(img, formatName, Base64.getEncoder().wrap(os));
            return os.toString(StandardCharsets.ISO_8859_1.name());
        } catch (final IOException ioe) {
            throw new UncheckedIOException(ioe);
        }
    }

    public static BufferedImage base64StringToImg(final String base64String) {
        try {
            return ImageIO.read(new ByteArrayInputStream(Base64.getDecoder().decode(base64String)));
        } catch (final IOException ioe) {
            throw new UncheckedIOException(ioe);
        }
    }

并截图

    final Robot robot = new Robot();
    final Rectangle r = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
    final BufferedImage bi = robot.createScreenCapture(r);
    final String base64String = Base64Converter.imgToBase64String(bi, "jpg");

2-我正在使用Gson库来字符串化对象

3-我正在bodyParser使用NodeJS

4-发送HTTP请求为:

public static void sendPOST(String image) throws Exception {
        String POST_PARAMS = "screenShotData";
        URL obj = new URL(POST_URL);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("POST");
        con.setConnectTimeout(5000); // 5 seconds
        con.setReadTimeout(5000); // 5 seconds

        Gson gson = new Gson();
        Http.ScreenShot screenShot = new ScreenShot(); // This is just a class with a string property
        screenShot.setImage(image);
        POST_PARAMS += gson.toJsonTree(screenShot).getAsJsonObject();


        con.setDoOutput(true);
        OutputStream os = con.getOutputStream();
        byte[] outputBytesArray = POST_PARAMS.getBytes();
        os.write(outputBytesArray);
        os.flush();
        os.close();


        int responseCode = con.getResponseCode();
        System.out.println("POST Response Code :: " + responseCode);

        if (responseCode == HttpURLConnection.HTTP_OK) { //success
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            Object responseObject = gson.fromJson(response.toString(), Object.class);
            System.out.println("Res: " + responseObject);
        } else {
            System.out.println(con.getResponseMessage());
        }
    }

标签: javanode.jsbase64content-type

解决方案


在 URL 编码文本中,该+字符表示空格字符。例如,

https://example.com/?s=nodejs+bodyparser

发送s带有值的参数

nodejs bodyparser 

(注意空格)。

当你做一个普​​通的表单发布(浏览器做的那种)时,你使用application/x-www-form-urlencoded数据类型,这意味着你的 POST 操作的有效负载看起来像一个查询字符串。我认为您将 JSON 对象作为文本字符串传递,而不对其进行 url 编码。

您可能想改用application/json数据类型。nodejs 的正文解析器从您的 Content-type 标头中检测到它是 JSON 并正确解析它。

尝试这个。(未调试,抱歉。)

    string payload = gson.toJsonTree(screenShot).getAsJsonObject();
    byte[] outputBytesArray = payload.getBytes();

    con.setRequestProperty("Content-Type", "application/json");
    con.setDoOutput(true);
    OutputStream os = con.getOutputStream();
    os.write(outputBytesArray);
    os.flush();
    os.close();

推荐阅读