JAVA筆記:Java網路編程(二)URL與URLConnection,

來源:互聯網
上載者:User

JAVA筆記:Java網路編程(二)URL與URLConnection,

URL的全稱是Uniform Resource Locator ,統一資源定位器,可以直接使用此類找到互連網上的資源。

URLConnection是封裝訪問遠程網路資源方法的類,通過它可以建立與遠程伺服器的串連,檢查遠端資源的一些屬性。

兩個執行個體:

URLConnection:

import java.net.URL ;import java.net.URLConnection ;import java.io.InputStream ;import java.util.Scanner ;public class URLConnectionDemo{public static void main(String args[]) throws Exception {// 所有異常拋出URL url = new URL("http://www.mldnjava.cn") ;URLConnection urlCon = url.openConnection() ;// 建立串連System.out.println("內容大小:" + urlCon.getContentLength()) ;System.out.println("內容類型:" + urlCon.getContentType()) ;}};

URL讀取頁面的IO流:

import java.net.URL ;import java.io.InputStream ;import java.util.Scanner ;public class URLDemo{public static void main(String args[]) throws Exception {// 所有異常拋出URL url = new URL("http","www.mldnjava.cn",80,"/curriculum.htm") ;InputStream input = url.openStream() ;// 開啟輸入資料流Scanner scan = new Scanner(input) ;// 執行個體化Scanner類scan.useDelimiter("\n") ;// 設定讀取分隔字元while(scan.hasNext()){System.out.println(scan.next()) ;}}};


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.