Java.net.URL學習總結

來源:互聯網
上載者:User

標籤:java   url   學習總結   

String host = "www.java2s.com";String file = "/index.html";String[] schemes = {"http", "https", "ftp", "mailto", "telnet", "file", "ldap", "gopher",        "jdbc", "rmi", "jndi", "jar", "doc", "netdoc", "nfs", "verbatim", "finger", "daytime",        "systemresource"};for (int i = 0; i < schemes.length; i++) {    try {        URL u = new URL(schemes[i], host, file);        System.out.println(schemes[i] + " is supported/r/n");    } catch (Exception ex) {        System.out.println(schemes[i] + " is not supported/r/n");    }}

結果為

http is supported/r/nhttps is supported/r/nftp is supported/r/nmailto is supported/r/ntelnet is not supported/r/nfile is supported/r/nldap is not supported/r/ngopher is not supported/r/njdbc is not supported/r/nrmi is not supported/r/njndi is not supported/r/njar is supported/r/ndoc is not supported/r/nnetdoc is supported/r/nnfs is not supported/r/nverbatim is not supported/r/nfinger is not supported/r/ndaytime is not supported/r/nsystemresource is not supported/r/n

URL.getContent()返回的是一個Object對象,可以用.getClass().getName()獲得這個對象實際的名字,如下代碼:(這裡在建立URL對象的時候,向構造方法裡傳的值,必須要以http://這個協議開頭,要不會拋出異常:java.net.MalformedURLException: no protocol: www.baidu.com)

URL url = new URL("http://www.baidu.com");Object content = url.getContent();System.out.println(content.getClass().getName());

以上代碼列印的是:

sun.net.www.protocol.http.HttpURLConnection$HttpInputStream


可以利用URL的openConnection方法,返回一個URLConnection對象,此對象可以用來擷取輸入資料流。

URL url = new URL("http://www.baidu.com");URLConnection urlConnection = url.openConnection();InputStream inputStream = urlConnection.getInputStream();int c ;while ((c = inputStream.read()) != -1) {    System.out.println((char)c);}inputStream.close();

或者用URL本身的openStream方法擷取輸入資料流。

URL url = new URL("http://www.baidu.com");//開啟到此 URL 的串連並返回一個用於從該串連讀入的 InputStream。InputStream in = url.openStream();int c;while ((c = in.read()) != -1)    System.out.print(c);in.close();


Java.net.URL學習總結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.