Binding local IP to Apache HttpClient 4

If you have more than two network cards on your machine and you would like to pick which one you would like to use with Apache HttpClient 4 then this guide will show you how to achieve it.

We can set which NIC to use by constructing a RequestConfig object. Here is an example below

			RequestConfig config = RequestConfig.custom().setLocalAddress(nicAddress).build();

setLocaAddress is the method responsible to telling HttpClient which network card to use on the current machine. We can then pass the config to the request as shown below

			HttpGet request = new HttpGet(url);

setLocalAddress takes in InetAddress as a parameter. In order to get the InetAddress for the desired NIC on your machine you can use the code below

			NetworkInterface nif = null;
			//you can use any of the following methods to get the NetworkInterface

after that you will get the InetAddress as shown below

			nifAddresses = nif.getInetAddresses();
			nicAddress = nifAddresses.nextElement();

Now you can use Apache HttpClient with any network interface card as you desire.

Leave a Reply

Your email address will not be published. Required fields are marked *