Can I override the Host header where using java

2019-01-12 05:16发布

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

3条回答
何必那么认真
2楼-- · 2019-01-12 05:45

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.

查看更多
做个烂人
3楼-- · 2019-01-12 06:01

The Host header is filled by the HttpURLConnection based on the URL. You can't open foo.com with Host=bar.com. From the RFC

The Host request-header field specifies the Internet host and port number of the resource being requested, as obtained from the original URI given by the user or referring resource (generally an HTTP URL)

Btw, you can also try apache http components.

查看更多
叼着烟拽天下
4楼-- · 2019-01-12 06:08

This is an issue with how volley handles HTTPUrlConnection and retry policy.

A Quick fix for it is to extend "HurlStack" class and override the "createConnection" function to return a HTTPUrlConnection with ChunkStreamMode of 0

public class CustomHurlStack extends HurlStack {


   public CustomHurlStack(){
       super();

   }

   @Override
   protected HttpURLConnection createConnection(URL url) throws IOException {
       HttpURLConnection connection = super.createConnection(url);
       connection.setChunkedStreamingMode(0);
       return connection;
   }

}

查看更多
登录 后发表回答