Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpURLConnection & Using A Specific Network Adapter

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?

like image 636
D-Dᴙum Avatar asked Feb 27 '12 18:02

D-Dᴙum


People also ask

What is HttpURLConnection used for?

The method is used to enable streaming of a HTTP request body without internal buffering, when the content length is not known in advance. The method is used to enable streaming of a HTTP request body without internal buffering, when the content length is known in advance.

What is HttpURLConnection in Java?

public abstract class HttpURLConnection extends URLConnection. A URLConnection with support for HTTP-specific features. See the spec for details. Each HttpURLConnection instance is used to make a single request but the underlying network connection to the HTTP server may be transparently shared by other instances.

What is the difference between URLConnection and HttpURLConnection?

URLConnection is the base class. HttpURLConnection is a derived class which you can use when you need the extra API and you are dealing with HTTP or HTTPS only. HttpsURLConnection is a 'more derived' class which you can use when you need the 'more extra' API and you are dealing with HTTPS only.

Is HttpURLConnection thread safe?

Each instance of HttpURLConnection may be used for one request/response pair. Instances of this class are not thread safe.


1 Answers

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_ADDRESS parameter 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.

like image 54
Oleg Mikheev Avatar answered Sep 22 '22 12:09

Oleg Mikheev