【问题标题】:Why does Content-Length HTTP header field use a value other than the one given in Java code?为什么 Content-Length HTTP 标头字段使用的值与 Java 代码中给出的值不同?
【发布时间】:2011-08-28 16:57:25
【问题描述】:

我有一段 Java 代码将字节数组传输到 HTTP 服务器:

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary="
    + myBoundary);
connection.setRequestProperty("Content-Length", 1024);

我使用这段代码来传输一个大小大于 1024 的字节数组。它运行良好。但是实际的 HTTP 消息(由Wireshark 捕获)显示 Content-Length 的值是实际大小而不是 1024。为什么?

我搜索了HTTP spec,但没有找到任何提示。我没有使用任何传输编码或传输编码。

【问题讨论】:

    标签: java http http-headers http-content-length


    【解决方案1】:

    我猜HttpURLConnection 会简单地用正确的值覆盖Content-Length 标头,因为它知道撒谎是不好的 ;-)

    事实上:在sun.net.www.protocol.HttpURLConnection 的第535-550 行,Content-Length 在适当的时候被设置。这发生在 用户指定的标头设置之后,因此该值将被覆盖。

    这是正确的:如果您传输的数据量与声称的数量不匹配,那么您只会混淆另一端。

    检查the source of sun.net.www.protocol.http.HttpURLConnection 似乎有一个标题列表受到限制,并且在调用setRequestProperty 时会被忽略。 Content-Length 就是其中之一。不幸的是,这似乎没有记录(至少我找不到任何关于此的文档,只有a discussion of a related problem here)。

    谷歌搜索 the ChangeSet that introduced this "functionality" 中提到的错误 ID (?) 似乎是作为对安全漏洞 CVE-2010-3541CVE-2010-3573 (Redhat bug on this topic) 的反应而引入的。

    可以通过在 JVM 启动时将系统属性 sun.net.http.allowRestrictedHeaders 设置为 true 来手动禁用限制。

    【讨论】:

    • Content-Length 的值被错误地硬编码。令我惊讶的是它有效。我想知道为什么。
    • 你的猜测听起来很合理。但是在哪里可以找到它的文档呢?
    • @joachim-sauer:很好的答案!但是我用 sun.net.http.allowRestrictedHeaders=true 测试过,结果和之前一样。
    • @wang:我的长期分析在这里并不适用,因为Content-Length 无论如何都会被正确的值覆盖。我已经更新了我的答案。
    【解决方案2】:

    这为我解决了:

    connection.setFixedLengthStreamingMode(myString.getBytes().length);
    conn.setRequestProperty("Content-length", String.valueOf(myString.getBytes().length));
    

    "connection.setFixedLengthStreamingMode(myString.getBytes().length);"在设置 Content-Length 标头之前。

    【讨论】:

      猜你喜欢
      • 2011-02-15
      • 1970-01-01
      • 1970-01-01
      • 2010-10-01
      • 1970-01-01
      • 2011-01-26
      • 2021-01-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多