假设我本机有多个网卡,因此有多个ip地址。我想在java请求http中如何选择我想要的ip地址(网卡)代码如下:package test;import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;public class HttpTest {
public static void main(String[] args) throws IOException {

//  拼凑get请求的URL字串,使用URLEncoder.encode对特殊和不可见字符进行编码
String getURL = "http://www.baidu.com";
URL getUrl = new URL(getURL);
//  根据拼凑的URL,打开连接,URL.openConnection函数会根据URL的类型,
//  返回不同的URLConnection子类的对象,这里URL是一个http,因此实际返回的是HttpURLConnection
HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
//  进行连接,但是实际上get request要在下一句的connection.getInputStream()函数中才会真正发到
//  服务器
connection.connect();
//  取得输入流,并使用Reader读取
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"gb2312"));//设置编码,否则中文乱码
String lines;
while ((lines = reader.readLine()) != null){
       lines = new String(lines.getBytes(), "gb2312");
System.out.println(lines);
}
reader.close();
//  断开连接
connection.disconnect(); }

}

解决方案 »

  1.   

    Enumeration<NetworkInterface> e=NetworkInterface.getNetworkInterfaces();
            while(e.hasMoreElements())
            {
                System.out.println(e.nextElement());
            }
    这个结果的第一个..
      

  2.   


    import java.net.InetAddress;
    import java.net.UnknownHostException;
    public class InetAddressDemo { public static void main(String[] args) throws UnknownHostException {

    InetAddress[] ips = InetAddress.getAllByName("本地的IP");
    for (InetAddress i : ips) {
    System.out.println(i.getHostAddress());
    }
    }}
      

  3.   

    你们这是枚举ip地址。我要的得到了ip(例如192.168.1.2)地址,如何绑定到HttpURLConnection去。证明这个http请求是使用192.168.1.2请求出去的。而不是默认地址(一台机器可能是多个地址)。
      

  4.   

    new InetSocketAddress(address[0],80); 做代理
      

  5.   

    这个问题是系统层的问题,Java是应用层,用代理应该不起作用。
    如果你的程序只访问固定的IP,最好是和管理员商量,修改本机的路由表,让访问那个IP地址的链接全部去你指定的那个网卡。
    例如:route -p add 目标IP mask 255.255.255.0 网卡IP