27

我正在使用以下代码在 java 中打开 http 连接:

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

但是,无论我调用方法的顺序如何,调用 conn.setRequestProperty("Host", "Test:8080") 似乎都没有效果,并且主机被重置为目标服务器。有没有办法在不使用其他库的情况下覆盖 Host 标头?

TIA 马特

4

3 回答 3

36

这在过去可以工作,但已作为安全修复的一部分被禁用。显然在更改日志中没有注释。在 bugs.sun.com上甚至还有像#7022056这样的错误。

另一个标题有一个类似的问题,答案更详细,所以我只是链接它而不是自己写。:-)

唯一的解决方法似乎是设置sun.net.http.allowRestrictedHeaderstrue使用另一个 http-library,例如已经提到的http components

于 2011-11-17T19:01:20.283 回答
8

Host头由HttpURLConnection基于 URL 的 填充。你不能foo.comHost=bar.com. 来自RFC

Host request-header 字段指定被请求资源的 Internet 主机和端口号,从用户给出的原始 URI 或引用资源(通常是 HTTP URL)获得

顺便说一句,你也可以试试apache http components

于 2011-10-04T13:57:01.323 回答
-2

这是 volley 如何处理 HTTPUrlConnection 和重试策略的问题。

一个快速的解决方法是扩展“HurlStack”类并覆盖“createConnection”函数以返回一个具有 0 的 ChunkStreamMode 的 HTTPUrlConnection

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;
   }

}

于 2015-03-18T18:16:38.067 回答