有 Java 编程相关的问题?

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

java Post BASE64到服务器

我正在尝试向服务器发送一个带有BASE64的映像,并且始终获得408,其中包含以下消息“请求正文未包含指定的字节数。获得13.140,预期为88.461”。我怎样才能解决这个问题

我试图使用改型,HttpURLConnection,但得到了相同的错误。我认为这是应用程序中的一些参数

 Gson gson = new Gson();
                    String jsonParam = gson.toJson(enviarPlataforma);

                    URL url = new URL("");
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");

                    conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
                    conn.setRequestProperty("Accept", "application/json");
                    conn.setDoOutput(true);
                    conn.setDoInput(true);
                    conn.setFixedLengthStreamingMode(jsonParam.getBytes().length);


                    Log.i("JSON", jsonParam.toString());
                    DataOutputStream os = new DataOutputStream(conn.getOutputStream());
                    os.writeBytes(jsonParam);

                    os.flush();
                    os.close();

                    Log.i("STATUS", String.valueOf(conn.getResponseCode()));
                    Log.i("MSG", conn.getResponseMessage());

                    conn.disconnect();
                } catch (Exception e) {
                    e.printStackTrace();
                }

共 (2) 个答案

  1. # 1 楼答案

    我解决我的问题。我不知道为什么,但当我使用Fiddler时,我收到了这个消息

    谢谢你们

  2. # 2 楼答案

    必须获取UTF-8字节,并按原样发送。DataOutputStream完全用于其他用途。由于这是一次写入,您可以简单地使用从连接获得的输出流。缓冲输出流可能没有任何用途

    不需要在收盘前冲水。一个人只需要站在一条连续的线上冲水

    Try with resources会自动关闭,也会在引发异常时关闭

                    conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
                    conn.setRequestProperty("Accept", "application/json");
                    conn.setDoOutput(true);
                    //conn.setDoInput(true);
    
                    byte[] content = jsonParam.getBytes("UTF-8"):
                    conn.setFixedLengthStreamingMode(content.length);
    
                    Log.i("JSON", jsonParam.toString());
                    try (OutputStream os = conn.getOutputStream()) {
                        os.write(content);
                    }