Java、HttpURLConnection 和设置内容长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7062349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 18:29:30  来源:igfitidea点击:

Java, HttpURLConnection and setting the content length

javaandroidhttpurlconnectioncontent-length

提问by SK9

I'm setting the length of the content in my HttpURLConnection, for a PUT.

我正在为 PUT 设置 HttpURLConnection 中内容的长度。

urlConnection.setRequestProperty("Content-Length", "" + responseJSONArray.toString(2).getBytes("UTF8").length);

The actual number of bytes is 74. However, when I query the content length of urlConnectionI'm returned -1. Why is that? And why are lengths not equal (given that I set this)?

实际字节数为 74。但是,当我查询urlConnection返回的内容长度时-1。这是为什么?为什么长度不相等(假设我设置了这个)?

I must set the content-length because I'm receiving a 411response from the server.

我必须设置内容长度,因为我正在接收411来自服务器的响应。

(Also, in the Sun examplesI've seen the second argument of setRequestPropertyis of type intand not String, which seems odd.)

(此外,在 Sun示例中,我看到了setRequestPropertyis 类型int而不是的第二个参数String,这似乎很奇怪。)

回答by user207421

You shouldn't set this header yourself. Use setFixedLengthStreamingMode()or setChunkedTransferMode().

你不应该自己设置这个标题。使用setFixedLengthStreamingMode()setChunkedTransferMode()

回答by Nicolas Modrzyk

Also do not forget to add a setDoOutputto tell your connection you are going to send data.

另外不要忘记添加一个setDoOutput来告诉您的连接您将要发送数据。

回答by Adrian S.

I get same error with "Content-Length" -

“内容长度”出现同样的错误 -

        URL url = new URL(targetURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "text/plain");
        connection.setRequestProperty("Authorization", authKey);
        connection.setRequestProperty("Content-Length", Integer.toString(requestJSON.getBytes().length));

And I finally deduced that it happens because one of the Json object fields contains diacritical characters.

我最终推断出它的发生是因为 Json 对象字段之一包含变音字符。

        someCategory = "?epu??";
        try {
        JSONObject postData = new JSONObject();
        postData.put("category", someCategory);
        .....

That's what the error looks like:

这就是错误的样子:

08-27 18:57:07.842 24263-24263/ro.nexuserp.documentecontabile E/Eror: content-length promised 491001 bytes, but received 491000