Question

I use Apache Commons HttpClient 3.1 as a kind of reverse-proxy. This proxy server runs in a servlet container in port 8081, and proxies some of the requests to port 8080 on the same server. As the legacy server on port 8080 builds some absolute urls using the HTTP Host header, I want to explicitly set that header.

It is not possible to set the Host-header as you set other headers, as HttpClient automatically overrides the value you set. The only way I've found to change the Host-header is to set the virtual host:

HttpClient = ...
HttpMethod = ...

HostParams hostParams = new HostParams();
hostParams.setVirtualHost("localhost:8081"); 
hostConfiguration.setParams(hostParams);
hostConfiguration.setHost("localhost", 8080);

client.executeMethod(hostConfiguration, method);

But this doesn't work as it should because HttpClient seems to add the port it connects to, to the Host:

11:07:05.011 [qtp1813719644-21] DEBUG httpclient.wire.header - >> "Host: localhost:8081:8080[\r][\n]"

Is it any way I can fix this behaviour? If not, does Apache Httpclient 4.x behave differently?

Was it helpful?

Solution

As your problem is traversing a proxy (which in your case is a Servlet+HTTPClient), configure your client to use localhost:8080 as proxy and url as normal: http://localhost:8081/... :

hostConfiguration.setProxy("localhost", 8080);
hostConfiguration.setHost("localhost", 8081);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top