Java - HttpURLConnection - 内容长度未显示在请求标头中

Ser*_*Pie 5 java post httprequest

我创建了一个普通的 HttpURLConnection 对象。例如,我设置了 3 个请求标头。

HttpURLConnection conn = (HttpURLConnection) someURL.openConnection();
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("User-Agent", "some_agent");
conn.setRequestProperty("Content-Type", "some_content-type");
conn.setRequestProperty("Content-Length", "some_content-length");
Run Code Online (Sandbox Code Playgroud)

我查看设置的请求标头。

System.out.println(conn.getRequestProperties());
Run Code Online (Sandbox Code Playgroud)

标头“Content-Length”永远不会包含在结果中。

{User-Agent=[some_agent], Content-Type=[some_content-type]}
Run Code Online (Sandbox Code Playgroud)

null如果我打电话,我也会得到 conn.getRequestProperty("Content-Length")

代码工作正常,但为什么“Content-Length”消失了?

raf*_*ian 6

您无法设置内容长度;它是自动完成的。但是,setFixedLengthStreamingMode()当预先知道内容长度时,您可以使用 , 。