如何在java.net.URLConnection上指定本地地址?

时间:2020-03-06 14:20:48  来源:igfitidea点击:

我的Tomcat实例正在侦听多个IP地址,但是我想控制打开" URLConnection"时使用的源IP地址。

我该如何指定呢?

解决方案

一种明显的可移植方法是在URL.openConnection中设置一个代理。该代理可以位于本地主机中,然后可以编写一个非常简单的代理来绑定客户端套接字的本地地址。

如果我们无法修改URL的连接源,则可以在调用URL构造函数时或者通过URL.setURLStreamHandlerFactory全局替换URLStreamHandler。然后,URLStreamHandler可以委派给默认的http / https处理程序,从而修改openConnection调用。

一种更极端的方法是完全替换处理程序(也许在JRE中扩展实现)。另外,也可以使用其他(开放源代码)http客户端。

这应该可以解决问题:

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);

我们完成了。
不要忘记很好地处理异常,当然,请更改值以适合情况。

嗯,我省略了导入语句

使用Apache Commons HttpClient,我还发现以下内容可以正常工作(为清楚起见,删除了try / catch):

HostConfiguration hostConfiguration = new HostConfiguration();
byte b[] = new byte[4];
b[0] = new Integer(192).byteValue();
b[1] = new Integer(168).byteValue();
b[2] = new Integer(1).byteValue();
b[3] = new Integer(11).byteValue();

hostConfiguration.setLocalAddress(InetAddress.getByAddress(b));

HttpClient client = new HttpClient();
client.setHostConfiguration(hostConfiguration);
GetMethod method = new GetMethod("http://remoteserver/");
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
    new DefaultHttpMethodRetryHandler(3, false));
int statusCode = client.executeMethod(method);

if (statusCode != HttpStatus.SC_OK) {
    System.err.println("Method failed: " + method.getStatusLine());
}

byte[] responseBody = method.getResponseBody();
System.out.println(new String(responseBody));");

但是,我仍然想知道如果IP网关关闭(在这种情况下为192.168.1.11)会发生什么情况。将尝试下一个网关还是失败?