网络编程-demo


  • 访问baidu首页的html内容
public class NetConnectionTest {

    public static void main(String[] args) throws Exception {
        URL url = new URL("http://www.baidu.com");
        BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
        String res = "";
        
        while(null!=(res = reader.readLine())){
            System.out.println(res);
        }
        reader.close();

    }

}
  • InetAddress
public class NetConnectionTest {

    public static void main(String[] args) throws Exception {
        InetAddress ia = InetAddress.getLocalHost();//访问本机
        System.out.println(ia);
        InetAddress baidu = InetAddress.getByName("www.baidu.com");//通过域名访问
        System.out.println(baidu);
    }

}

你可能感兴趣的:(网络编程-demo)