8

I want to send an HTTP request using Spring RestTemplate, via the exchange method.

The third parameter is an instance of HttpEntity, which allows setting the headers/body of the request. I tried the following code snippet:

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

Notice that http://httpbin.org/headers is a simple HTTP Request & Response Service, which (in this case) returns HTTP headers.

The result of running the Java code is as follows:

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

As you can see, the User-Agent is set to what I wanted, but the Host is not.

How can I set Host to the value I desire?

2
  • I'm not sure you can--it doesn't usually make sense to set the Host header to something different from the URI. Commented Apr 5, 2017 at 6:30
  • @chrylis: Thanks for the comment. In my use case, I'm writing a reverse proxy for some host H. The proxy is to be hosted at host H, and will contact the actual host H by IP. However, as the actual host H uses virtual hosting, I have to specify the host name H in my request (i.e., the request from the reverse proxy to the IP address). Commented Apr 5, 2017 at 6:42

1 Answer 1

4

Perhaps this helps. I don't know if the underlying http call is made through HttpUrlConnection, but setting sun.net.http.allowRestrictedHeaders to true might be worth trying.

See:

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much; you saved my day! Setting System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); seems to work perfectly.
Beware! You've asked a question about Spring RestTemplate, but this fix is about Sun HttpURLConnection. If you configure RestTemplate with an Apache ConnectionFactory (which is a very good idea), this fix becomes irrelevant.
I followed this example to reconfigure RestTemplate and use Appache http client which can override the host header without any issues. springframework.guru/using-resttemplate-with-apaches-httpclient

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.