Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

557
Views
Setting "Host" header for Spring RestTemplate doesn't work

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?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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:

  • Can I override the Host header where using java's HttpUrlConnection class?
  • How to overwrite http-header "Host" in a HttpURLConnection?
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!