Java 中网络相关 API:InetAddress、URL 的应用

来源:互联网 发布:四川大学校内网络电视 编辑:程序博客网 时间:2024/05/18 02:02

Java 中网络相关 API 的应用

(1)Java 中的 InetAddress 的应用 (此类表示互联网协议(IP) 地址),使用方法如下:

public class InetAddressDemo {    public static void main(String[] args) throws UnknownHostException {        //获取本机的InetAddress实例        InetAddress address1=InetAddress.getLocalHost();        System.out.println("主机名:"+address1.getHostName());        System.out.println("IP地址:"+address1.getHostAddress());        System.out.println("......................................");        // 根据机器名获取InetAddress实例        InetAddress address2=InetAddress.getByName("169.254.229.169");        System.out.println("主机名:"+address2.getHostName());        System.out.println("IP地址:"+address2.getHostAddress());    }}

这里写图片描述


(2)Java 中的 URL 的应用

//URL常用方法public class URLDemo {    public static void main(String[] args) throws MalformedURLException {        URL url=new URL("https://www.so.com/s?ie=utf-8&shb=1&src=360sou_newhome&q=socket%E7%BC%96%E7%A8%8B");        System.out.println("协议:"+url.getProtocol());        System.out.println("主机:"+url.getHost());        System.out.println("端口:"+url.getPort());        System.out.println("文件路径:"+url.getPath());        System.out.println("文件名:"+url.getRef());        System.out.println("查询字符串:"+url.getQuery());    }}

这里写图片描述

//URL操纵网络中的资源public class URLonlineDemo {    public static void main(String[] args) throws IOException {        //创建一个URL实例        URL url=new URL("http://www.baidu.com");        //通过URL中的openStream方法获取URL对象所表示的资源的字节输入流        InputStream inputStream=url.openStream();        //将字节输入流转化为字符输入流        InputStreamReader inputStreamReader=new InputStreamReader(inputStream,"UTF-8");        //为字符输入流添加缓冲        BufferedReader bufferedReader=new BufferedReader(inputStreamReader);        String data=bufferedReader.readLine();        while(null!=data){            System.out.println(data);            data=bufferedReader.readLine();        }        bufferedReader.close();        inputStreamReader.close();        inputStream.close();    }}

这里写图片描述

0 0
原创粉丝点击