【问题标题】:Java - HttpURLConnection - Content-Length isn't shown in request headerJava - HttpURLConnection - 内容长度未显示在请求标头中
【发布时间】:2013-09-07 14:10:51
【问题描述】:

我创建了一个普通的 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");

我查看设置的请求标头。

System.out.println(conn.getRequestProperties());

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

{User-Agent=[some_agent], Content-Type=[some_content-type]}

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

代码运行良好,但为什么“Content-Length”消失了?

【问题讨论】:

  • 设置 Content-Length 没有多大意义,因为它是由您尝试访问的 URL 控制的。
  • @JoshM 在 POST(或 PUT)中,需要设置请求体的 Content-Length。

标签: java post httprequest


【解决方案1】:

你不能设置内容长度;它是自动完成的。但是,如果事先知道内容长度,您可以使用setFixedLengthStreamingMode()

【讨论】:

【解决方案2】:

你需要设置System.setProperty("sun.net.http.allowRestrictedHeaders", "true");

有关它的更多详细信息(类似问题): https://community.oracle.com/thread/1999694?tstart=0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多