网络编程--常用API

来源:互联网 发布:乔丹各赛季数据统计 编辑:程序博客网 时间:2024/05/02 05:06

InetAddress类

该类用于标识网络上的硬件资源,表示互联网协议的IP地址
该类没有构造方法,所以不能直接new出一个对象,可以通过该类的静态方法获得InetAddress的对象

public class IPDemo {    public static void main(String[] args) throws UnknownHostException {        // 1..获取本机的InetAddress实例        InetAddress local = InetAddress.getLocalHost();        System.out.println("本机名称:"+local.getHostName());        System.out.println("本机IP:"+local.getHostAddress());        byte[] buf = local.getAddress();        System.out.println("IP的字节数组:"+Arrays.toString(buf));        // 2..根据机器名获取InetAddress实例        InetAddress addre1 = InetAddress.getByName("www.ytu.edu.cn");           System.out.println("该机器名对应的IP:"+addre1.getHostAddress());        // 3..根据IP获取InetAddress实例        InetAddress addre2 = InetAddress.getByName("202.194.116.18");        System.out.println("该IP对应的机器名:"+addre2.getHostName());        byte[] addr = {(byte) 202,(byte)194,(byte)116,(byte)18};    }}                 

URL类

URL 统一资源定位符,表示Internet上某一资源的地址

public class UrlDemo {    public static void main(String[] args) throws Exception {        URL url1 = new URL("https://127.0.0.1:8080");  //创建一个url实例        URL url = new URL(url1,"test/index.htm?usrname=nc");  //根据已有url创建新的url实例        System.out.println("协议:"+url.getProtocol());        System.out.println("主机地址:"+url.getHost());        //获取端口,如果未指定端口号,则使用默认的端口号80,使用默认的端口号调用getPort()方法返回的值为-1        System.out.println("端口:"+url.getPort());        System.out.println("文件路径:"+url.getPath());        System.out.println("文件名:"+url.getFile());        System.out.println("查询字符串:"+url.getQuery());    }}
//InputStream openStream() //打开到此 URL 的连接并返回一个用于从该连接读入的 InputStream//使用该方法获取网页源码 public class UrlDemo {    public static void main(String[] args) throws Exception {        // TODO 自动生成的方法存根        URL url = new URL("http://www.sina.com.cn");        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(),"utf-8"));        byte[] buf = new byte[1024];        String line = null;        while((line = in.readLine())!=null)        {            System.out.println(line);        }        in.close();    }}
原创粉丝点击