I need to make an HTTP request with specific Host header that may differ from destination address. What are my options?
Let's say we have these variables already defined.
String host = "https://example.com/something";
String destination_address = "https://8.8.8.8";
String http_version = "HTTP/2";
String http_method = "POST";
boolean follow_redirects = true;
Here is my code. Currently i am using Apache Http-Client-5, but i don't mind hearing any other suggestions.
H2AsyncClientBuilder builder_2 = HttpAsyncClients.customHttp2();
if (follow_redirects) {
builder_2.setRedirectStrategy(new DefaultRedirectStrategy());
}
if (!(Objects.equals(destination_address, host))) {
builder_1.setProxy(HttpHost.create(destination_address));
}
CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
client = builder_2.build();
client.start();
// Here i have long "case" statement for each Http method, i desided to not enclude it here.
// Here is the version for post request.
http_request = SimpleRequestBuilder.post(host)
.setBody(request_body, ContentType.TEXT_PLAIN)
.setHeaders(request_headers)
.build();
Future<SimpleHttpResponse> future = client.execute(http_request, null);
SimpleHttpResponse http_response = future.get();
client.close(CloseMode.GRACEFUL);
There's no requirement for Host
header to match target URL, otherwise shared hosting would not work. But there's more - your host
variable holds full URL string, while host name should be just what it says example.com
:
String host = "example.com";
String destination_address = "https://8.8.8.8";
Once that is corrected, create custom header and use it while building request:
Header hostHeader = new BasicHeader(HttpHeaders.HOST, host);
http_request = SimpleRequestBuilder.post(destination_address + "/something")
.setBody(request_body, ContentType.TEXT_PLAIN)
.addHeader(hostHeader) // Add the custom 'Host' header
.setHeaders(request_headers)
.build();
I am using Apache HttpClient's BasicHeader
class.