Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I specify the local address on a java.net.URLConnection?

My Tomcat instance is listening to multiple IP addresses, but I want to control which source IP address is used when opening a URLConnection.

How can I specify this?

like image 429
stian Avatar asked Sep 18 '08 11:09

stian


People also ask

What is URL and URLConnection in Java?

The Java URLConnection class represents a communication link between the URL and the application. It can be used to read and write data to the specified resource referred by the URL.

How do I make a connection to URL in Java?

connect method is called. When you do this you are initializing a communication link between your Java program and the URL over the network. For example, the following code opens a connection to the site example.com : try { URL myURL = new URL("http://example.com/"); URLConnection myURLConnection = myURL.

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.


1 Answers

This should do the trick:

URL url = new URL(yourUrlHere);
Proxy proxy = new Proxy(Proxy.Type.DIRECT, 
    new InetSocketAddress( 
        InetAddress.getByAddress(
            new byte[]{your, ip, interface, here}), yourTcpPortHere));
URLConnection conn = url.openConnection(proxy);

And you are done. Dont forget to handle exceptions nicely and off course change the values to suit your scenario.

Ah and I omitted the import statements

like image 138
Javaxpert Avatar answered Oct 20 '22 01:10

Javaxpert