Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpURLConnection won't let me set "Via" header

I'm trying to use a java.net.HttpURLConnection to make an HTTP request to a server. One of the HTTP headers I need to send is "Via". In my code there is something like this:

connection.addRequestProperty("X-test", "test_header_contents"); // just a sanity test
connection.addRequestProperty("Via", "via_header_contents");

When I use a packet sniffer, I can see that the test header is going through but the via header is not. I know that Via is a "restricted" header, so I added this line:

System.setProperty("sun.net.http.allowRestrictedHeaders", "true");

This line worked when I had the same problem in the past, but it is not working now. I know that the system property gets set, because I call System.getProperty right before I try to add the HTTP headers and it returns true. Is there something else I should be doing to be able to send the via header? Like I said, this worked before but doesn't now. I think the only thing that changed is that I moved from Java 6 to 7. Thanks for any help you can give me.

like image 585
user1473404 Avatar asked Jun 21 '12 21:06

user1473404


3 Answers

Answering my own question.

The problem is that I was setting system property sun.net.http.allowRestrictedHeaders too late in the program. I set it immediately before I attempted to send the headers, and that was too late, apparently because HttpURLConnection does some kind of caching of the properties. By setting the property at the beginning of the program I was able to make it all work.

like image 183
user1473404 Avatar answered Oct 14 '22 01:10

user1473404


The source code for OpenJDK 7 (build 43) shows that they use a static initialization block to set this property and then cache the value. So you need to set the property before it is set. This means it needs to be set before the HttpURLConnection class is first loaded.

like image 4
David V Avatar answered Oct 14 '22 00:10

David V


I have the same problem withe "Trailer" header

I also use:

 System.setProperty("sun.net.http.allowRestrictedHeaders", "true");

I do it in the static constructor of the main class and pass with the JVM parameters

<PARAM name="java_arguments" value="-Dsun.net.http.allowRestrictedHeaders=true">

It works if I run the applet from Eclipse, but does not work when run from the browser

like image 2
Alexandr Avatar answered Oct 14 '22 01:10

Alexandr