Java, HttpURLConnection and setting the content le

2019-04-04 10:27发布

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

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 urlConnection I'm returned -1. Why is that? And why are lengths not equal (given that I set this)?

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

(Also, in the Sun examples I've seen the second argument of setRequestProperty is of type int and not String, which seems odd.)

3条回答
Explosion°爆炸
2楼-- · 2019-04-04 10:39

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.

        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
查看更多
淡お忘
3楼-- · 2019-04-04 10:59

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

查看更多
Summer. ? 凉城
4楼-- · 2019-04-04 11:00

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

查看更多
登录 后发表回答