2017-04-05 133 views
0

我想通過使用Spring RestTemplate,通過exchange方法發送HTTP請求。爲Spring RestTemplate設置「主機」標題不起作用

第三個參數是HttpEntity的一個實例,它允許設置請求的標頭/正文。我嘗試下面的代碼片斷:

import org.springframework.http.*; 
import org.springframework.web.client.RestTemplate; 

public class Connector { 
    public static void main(String[] args) { 

     HttpHeaders headers = new HttpHeaders(); 
     headers.set("Host", "www.example.com"); 
     headers.set("User-Agent", "whatever"); 


     RestTemplate restTemplate = new RestTemplate(); 

     ResponseEntity<String> responseEntity = restTemplate.exchange(
       "http://httpbin.org/headers", HttpMethod.GET, 
       new HttpEntity<String>(null, headers), String.class); 

     System.out.println(responseEntity.getBody()); 
    } 
} 

注意http://httpbin.org/headers是一個簡單的HTTP請求&響應服務,它(在這種情況下)返回的HTTP標頭。

運行Java代碼的結果如下:

{ 
    "headers": { 
    "Accept": "text/plain, */*", 
    "Connection": "close", 
    "Host": "httpbin.org", 
    "User-Agent": "whatever" 
    } 
} 

正如你所看到的,User-Agent設置爲我想要的東西,但Host不是。

如何將Host設置爲我想要的值?

+0

我不知道你可以 - 它通常不會有意義了'Host'頭設置的東西從不同URI。 – chrylis

+0

@chrylis:感謝您的評論。在我的使用案例中,我正在爲某個主機H寫一個反向代理。代理將託管在主機H上,並將通過IP與實際主機H聯繫。但是,由於實際主機H使用虛擬主機,我必須在我的請求中指定主機名稱H(即從反向代理到IP地址的請求)。 –

回答

1

也許這會有所幫助。我不知道底層http調用是否通過HttpUrlConnection創建,但將sun.net.http.allowRestrictedHeaders設置爲true可能值得嘗試。

參見:

+0

非常感謝你;你救了我的一天!設置'System.setProperty(「sun.net.http.allowRestrictedHeaders」,「true」);'似乎完美。 –

+0

小心!你已經提出了一個關於Spring RestTemplate的問題,但是這個修補程序是關於Sun HttpURLConnection的。如果您使用Apache ConnectionFactory配置RestTemplate(這是一個非常好的主意),此修復將變得無關緊要。 – slim