简体   繁体   中英

Java - HttpURLConnection - Content-Length isn't shown in request header

I create a normal HttpURLConnection-object. I set for example 3 request headers.

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");

I look at setted request headers.

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

The header "Content-Length" is never contained in the result.

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

I am getting also null if I call conn.getRequestProperty("Content-Length") .

The code works fine but why does "Content-Length" disappear?

You can't set the content length; it's done automatically. You can, however, use setFixedLengthStreamingMode() , when the content length is known in advance.

You need to set up System.setProperty("sun.net.http.allowRestrictedHeaders", "true");

More details about it(similar issue): https://community.oracle.com/thread/1999694?tstart=0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM