網路程式設計之 URL 下載網路資源
阿新 • • 發佈:2020-11-21
URL【統一資源定位符】:定位資源的,定位網際網路上的某一個資源。
DNS 域名解析:www.baidu.com【某一域名】指向 39.156.69.79【某一網站空間IP】
URL 組成:協議://ip地址:埠/專案名/資源
URL:統一資源定位符
package lesson04; import java.net.MalformedURLException; import java.net.URL; /** * URL:統一資源定位符 */ public class URLDemo1 { public static void main(String[] args) throwsMalformedURLException { URL url = new URL("http://localhost:8080/helloworld/index.jsp?username=kuangshen&password=123"); //協議名 System.out.println(url.getProtocol()); //主機名-主機ip System.out.println(url.getHost()); //埠 System.out.println(url.getPort());//地址-檔案路徑 System.out.println(url.getPath()); //檔案-全路徑 System.out.println(url.getFile()); //查詢部分-引數 System.out.println(url.getQuery()); } }
URL下載資源
package lesson04; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection;import java.net.URL; /** * URL下載資源 */ public class URLDown { public static void main(String[] args) throws Exception { //1、下載地址 URL url = new URL("https://m10.music.126.net/20201121104035/2c5eb73ce4421a090b62647f6c486e2c/yyaac/obj/wonDkMOGw6XDiTHCmMOi/3625445007/7d37/4109/d0ef/d56e8176f5789a4e6f8b2173ce500bf6.m4a"); //2、連線到這個資源 HTTP HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); InputStream inputStream = urlConnection.getInputStream(); FileOutputStream fos = new FileOutputStream("f6.m4a"); byte[] buffer = new byte[1024]; int len; while ((len = inputStream.read(buffer)) != -1){ fos.write(buffer, 0, len); //寫出這個資料 } //關閉 fos.close(); inputStream.close(); //斷開連線 urlConnection.disconnect(); } }
效果一覽