I’d like to use the Java class HttpURLConnection to connect to a particular device on a (local network). I have need to use a specific network adapter because the machine that will be running my program has 2 network adapters installed. One adapter is on a wider company network and is dynamically assigned an IP whilst the second is a network local to the machine and has a static IP. It is this second local network to which I want to restrict my program to.
Using HttpURLConnection is convenient because it relieves me of having to parse the server response etc and get straight at the data I need instead of doing something like this. However because I need to restrict my HTTP requests to a specific network adapter I can’t be 100% sure that my HTTP requests are sent ONLY via the desired adapter. Am I correct in my understanding of how HttpURLConnection works i.e. it relies on the operating system to select the appropriate network adapter to use?
With plain Java you will only be able to bind a Socket to a selected NetworkInterface.
If you need HTTP protocol support with ability to control which network interface to connect from you’ll need to use Apache HTTP Client.
You’ll need to provide a
ConnRoutePNames.LOCAL_ADDRESSparameter to it, see details here: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html.UPDATE:
Since 4.3 ConnRoutePNames is deprecated, please use RequestConfig and its RequestConfig.Builder instead.