zoukankan      html  css  js  c++  java
  • 创建和使用URL访问网络资源

    public class URLTest

    {

        public static void main(String[] args) throws Exception

        {

           URL url = new URL(

                   "http://java.sun.com:80/docs/books/tutorial/index.html#DOWN");

     

           String protocal = url.getProtocol();

     

           String path = url.getPath();

     

           String host = url.getHost();

     

           String file = url.getFile();

     

           int port = url.getPort();

     

           String ref = url.getRef();

     

           System.out.println(protocal + ", " + host + ", " + port + ", " + file

                  + ", " + ref);

     

           System.out.println(path);

        }

    }

     

     

    打开一个url连接,用字节流获得它首页的信息

    public class UrlConnectionTest

    {

        public static void main(String[] args) throws Exception

        {

           URL url = new URL("http://localhost");

          

           /*URLConnection con = url.openConnection();

          

           InputStream is = con.getInputStream();*/

          

            InputStream is = url.openStream();

          

           OutputStream os = new FileOutputStream("infoq.html");

          

           byte[] buffer = new byte[2048];

          

           int len = 0;

          

           while(-1 != (len = is.read(buffer,0,buffer.length)))

           {

               os.write(buffer,0,buffer.length);

           }

          

           is.close();

           os.close();

        }

    }

     

    用字符流获得Url打开后得到的信息

    public class UrlConnectionTest2

    {

        public static void main(String[] args) throws Exception

        {

           URL url = new URL("http://localhost");

          

           BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));

          

           String line = null;

          

           while(null != (line = br.readLine()))

           {

               System.out.println(line);

           }

          

           br.close();

        }

    }

     

    InetAddress类,用于获取连接的IP地址

    public class InetAddressTest

    {

        public static void main(String[] args) throws Exception

        {

           InetAddress address = InetAddress.getLocalHost();

          

           System.out.println(address);

          

           address = InetAddress.getByName("www.sohu.com");

          

           System.out.println(address);

        }

    }

     

     

  • 相关阅读:
    MySQL全面瓦解20:可编程性之流程控制语句
    MySQL全面瓦解19:游标相关
    MySQL全面瓦解18:自定义函数
    MySQL全面瓦解17:触发器相关
    MySQL全面瓦解16:存储过程相关
    MySQL全面瓦解15:视图
    MySQL全面瓦解14:事务
    MySQL全面瓦解13:系统函数相关
    MySQL全面瓦解12:连接查询的原理和应用
    MySQL全面瓦解11:子查询和组合查询
  • 原文地址:https://www.cnblogs.com/zfc2201/p/2143622.html
Copyright © 2011-2022 走看看