0

I am using Apache httpClient library in my android project to send get/post requests to the server. My server is set up using apache namevirtualhost - there are multiple virtual hosts on the same server.

For those not familiar with how apache namevirtualhost works, the simple explanation is that there are multiple configurations defined in the server config, and apache uses Host request header to determine which configuration to use. When multiple hosts are defined, the first one is considered default and all requests with Host request header not explicitly matching one of the defined namevirtualhosts will be handled using the default configuration.

Now, the server I'm trying to connect to is not the default one. When my app runs and the request is made to the server, it does not go to my virtual host but instead is handled by the default one, resulting in the certificate name mismatch. (Note that I do have the correct certificates set up.)

Here's my code - copy/paste, except for the actual URL:

String targetUrl = getTargetUrl();
//this returns something like https://www.example.com/api/1/orders (without spaces, of course)
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(targetUrl);

List<NameValuePair> data = new ArrayList<NameValuePair>(1);
data.add(new BasicNameValuePair("orders", json.toString()));
data.add(new BasicNameValuePair("username", username));
data.add(new BasicNameValuePair("password", password));
post.setEntity(new UrlEncodedFormEntity(data));
HttpResponse response = client.execute(post);

This results in an error message saying that certificate name doesn't match the requested url and shows the requested url and the certificate url - the certificate url is the default one in the apache config.

I added this code right before the line to execute the request:

Header[] hds = post.getAllHeaders();
for(Header h : hds) {
    Log.d("PasteneOrers", h.getName() + ": " + h.getValue());
}

to see what headers are included. Interesting, Host header is not shown. I then added this code before executing the request:

URL url = new URL(targetUrl);
post.setHeader("Host", url.getHost());

Now the above debugging output correctly shows the Host header - but it doesn't help and the request is still going to the default one.

To verify that this is not a problem with the server misconfiguration, I copied the target URL and pasted it into the browser running on the same android emulator - this works correctly and I get the right results. Hence it's definitely something in my code - but what? At this point I'm stuck. Any suggestions would be appreciated.

Aleks G
  • 56,435
  • 29
  • 168
  • 265

1 Answers1

0

In the interest of others having this problem, I couldn't resolve it with apache httpclient. I switched to using HttpUrlConnection and everything worked correctly.

Aleks G
  • 56,435
  • 29
  • 168
  • 265