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

后端 未结 4 1257
名媛妹妹
名媛妹妹 2020-12-01 06:50

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

4条回答
  •  没有蜡笔的小新
    2020-12-01 07:37

    The obvious portable way would be to set a Proxy in URL.openConnection. The proxy can be in local host, you can then write a very simple proxy that binds the local address of the client socket.

    If you can't modify the source where the URL is connected, you can replace the URLStreamHandler either when calling the URL constructor or globally through URL.setURLStreamHandlerFactory. The URLStreamHandler can then delegate to the default http/https handler, modifying the openConnection call.

    A more extreme method would be to completely replace the handler (perhaps extending the implementation in your JRE). Alternatively, alternative (open source) http clients are available.

提交回复
热议问题