java中讲讲URL的用法,举例?

4.URL类的实例

马克-to-win:URL(Uniform Resource Locator-----一致资源查找器)它用来指向Internet上的资源文件,比如 http://java.sun.com:8080/docs/introdiction.htm net包中的URL类提供API来访问Internet上的信息。

比如以上的URL中:
1)协议:http
2)IP 地址或主机名:java.sun.com
3)端口号:8080
4)实际文件路径:docs/introdiction.htm

例:2.4.1
/*no need to have network through to run the program.*/
import java.net.*;
import java.io.*;
public class TestMark_to_win {
    public static void main(String[] args) throws Exception {
        /* Class URL represents a Uniform Resource Locator, a pointer to a
         * "resource" on the World Wide Web. A resource can be something as
         * simple as a file or a directory, public URL(String spec)throws
         * MalformedURLException: Creates a URL object from the String
         * representation.
         */
        URL aURL = new URL("http://java.sun.com:8080/docs/books/"
                + "tutorial/index.html");
        System.out.println("protocol = " + aURL.getProtocol());
        System.out.println("host = " + aURL.getHost());
        System.out.println("filename = " + aURL.getFile());
        System.out.println("default port = " + aURL.getDefaultPort());
        System.out.println("port = " + aURL.getPort());
    }
}

 

例:2.4.2

/* This program needs an open connection to run.
*/
import java.net.*;
import java.io.*;
import java.util.*;
public class TestMark_to_win {
    public static void main(String[] args) throws Exception {
        URL yahoo = new URL("https://www.oracle.com/index.html");
        /* public URLConnection openConnection() throws IOException: Returns a
         * URLConnection object that represents a connection to the remote
         * object referred to by the URL.
         */
        URLConnection yahooConnection = yahoo.openConnection();
        /* public long getLastModified() Returns the value of the last-modified
         * header field. The result is the number of milliseconds since January
         * 1, 1970 GMT.
         */
        System.out.println("content LastModified"
                + new Date(yahooConnection.getLastModified()));
        /*public InputStream getInputStream()throws IOException: Returns an
         * input stream that reads from this open connection.
         */
        // DataInputStream in = new
        // DataInputStream(yahooConnection.getInputStream());
        BufferedReader in = new BufferedReader(new InputStreamReader(
                yahooConnection.getInputStream()));
        String inputLine;
        for (int i = 0; i < 25; i++) {
            inputLine = in.readLine();
            System.out.println(inputLine);
        }
        in.close();
    }
}

更多请见:http://www.mark-to-win.com/tutorial/java_9_URLExample.html

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值