Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I override the Host header where using java's HttpUrlConnection class?

I'm using the following code to open a http connection in java:

 URL url = new URL("http://stackoverflow.com");  HttpURLConnection conn = (HttpURLConnection) url.openConnection();  conn.setDoOutput(true);  conn.setRequestMethod("GET");  conn.setRequestProperty("Host", "Test:8080");  conn.getOutputStream(); 

However calling conn.setRequestProperty("Host", "Test:8080") appears to have no effect regardless of what order I call the methods and the Host is reset to the destination server. Is there any way to override the Host header without using a different library?

TIA Matt

like image 689
Matt Avatar asked Oct 04 '11 13:10

Matt


People also ask

How do I set headers in HttpURLConnection?

URL url = new URL(urlToConnect); HttpURLConnection httpUrlConnection = (HttpURLConnection) url. openConnection(); Step 2: Add headers to the HttpURLConnection using setRequestProperty method.

Do I need to disconnect HttpURLConnection?

Yes you need to close the inputstream first and close httpconnection next. As per javadoc.

Which method of HttpURLConnection class is used to retrieve the response status from server?

Get the request method. Gets the status code from an HTTP response message. Gets the HTTP response message, if any, returned along with the response code from a server. This method is used to enable streaming of a HTTP request body without internal buffering, when the content length is not known in advance.

What is the use of HttpURLConnection in Java?

HttpURLConnection class is an abstract class directly extending from URLConnection class. It includes all the functionality of its parent class with additional HTTP-specific features. HttpsURLConnection is another class that is used for the more secured HTTPS protocol.


1 Answers

This used to work in the past, but it has been disabled as part of a security-fix. Apparently without a note in the changelog. There are even bugs like #7022056 for this at bugs.sun.com.

There is a similar question for another header, where the answer goes more into the details, so I just link it instead of writing it myself. :-)

The only workarounds seem to be setting sun.net.http.allowRestrictedHeaders to true or use another http-library like the already mentioned http components.

like image 96
Boris Avatar answered Oct 06 '22 01:10

Boris