Java HttpURLConnection 未发送 body

Java HttpURLConnection is not sending a body

我正在尝试使用 Java 将带有 body 的 PUT 请求发送到我的 Android 应用程序中的 API。我正在使用 java.net HttpURLConnection 并且请求通过了。但是没有 body.

我一遍又一遍地重构我的代码,但它仍然不起作用,目前我有以下任务:

@Override
protected String doInBackground(String... urls) {
      String result = "";
      URL url;
      HttpURLConnection urlConnection = null;
      JSONObject body = new JSONObject();
      try {
          body.put("title", title);
          body.put("content", content);
          try {
              url = new URL(urls[0]);
              urlConnection = (HttpURLConnection) url.openConnection();
              urlConnection.setRequestMethod("PUT");
              urlConnection.addRequestProperty("username", username);
              urlConnection.addRequestProperty("password", password);
              urlConnection.addRequestProperty("Content-Type", "application/json; utf-8");
              urlConnection.addRequestProperty("Accept", "application/json");
              urlConnection.setDoOutput(true);

              try(OutputStream os = urlConnection.getOutputStream()){
                  byte[] input = body.toString().getBytes("utf-8");
                  os.write(input, 0, input.length);
              }

              InputStream in = urlConnection.getInputStream();
              InputStreamReader reader = new InputStreamReader(in);
              int data = reader.read();
              while (data != -1){
                  char current = (char) data;
                  result += current;
                  data += current;
                  data = reader.read();
              }
              return result;
          }catch (Exception e){
              e.printStackTrace();
              return null;
          }
      } catch (JSONException e) {
          e.printStackTrace();
          return  null;
      }
}

但是这段代码总是导致一个空 body。

编辑

将内容类型更改为 application/x-www-form-urlencoded 时,服务器获得 body。但是这样我就没有得到一个 JSON 文件来进一步处理它。

java 代码运行正常。 API 不接受 JSON。其他语言没有问题。

服务器信息

  • Node.js
  • 快递
  • 正文分析器

我没有添加app.use(bodyParser.json());