Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java: Http request with different Host Header and destination

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

There’s no requirement for Host header to match target URL, otherwise shared hosting would not work. But there’s more flaw – your host variable holds fuld URL string, while host name should be just example.com:

String host = "example.com";
String destination_address = "https://8.8.8.8";

Then create custom header and use it while creating 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading