Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, HttpURLConnection and setting the content length

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.)

like image 809
SK9 Avatar asked Aug 15 '11 06:08

SK9


2 Answers

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

like image 99
user207421 Avatar answered Sep 21 '22 21:09

user207421


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

like image 37
Nicolas Modrzyk Avatar answered Sep 25 '22 21:09

Nicolas Modrzyk