Java URL基础用法示例

前言:基础示例小记。
原文出处:http://blog.csdn.net/u014158743/article/details/52938786

public static void main(String[] args) throws IOException {

    String path = "http://localhost:8080/myweb/mail.html?name=lisi";

    URL url = new URL(path);
    System.out.println(url.getProtocol());//获取协议
    System.out.println(url.getHost());//获取主机
    System.out.println(url.getPort());//获取端口
    System.out.println(url.getPath());//得到资源路径/myweb/mail.html
    System.out.println(url.getFile());///myweb/mail.html?name=lisi

    URLConnection conn = url.openConnection();//和服务器端连接

    //读取服务器发回的数据
    InputStream in = conn.getInputStream();
    byte[] arr = new byte[1024];
    int len = in.read(arr);
    System.out.println(new String(arr,0,len));

}

更多方法解释参考这里

猜你喜欢

转载自blog.csdn.net/u014158743/article/details/52938786