URL
https://www.baidu.com/
统一资源定位符:定位资源的,定位互联网上的某一个资源
DNS域名解析 www.baidu.com -> xxxx.xxxx.xxxx.xxxx
协议: //ip地址:端口/项目名/资源
package com.hua; import java.net.MalformedURLException; import java.net.URL; public class URLDemo01 { public static void main(String[] args) throws Exception { URL url = new URL("http://localhost:8080/helloworld/index.jsp?username=kuangshen&password=123"); System.out.println(url.getProtocol());//协议 System.out.println(url.getHost());//主机IP System.out.println(url.getPort());//端口 System.out.println(url.getPath());//全路径 System.out.println(url.getFile());//文件 System.out.println(url.getQuery());//参数 }
package com.hua; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; public class URLDown { public static void main(String[] args) throws Exception { //1、下载地址 URL url = new URL("https://cambrian-images.cdn.bcebos.com/ca301075b8ec31caeffd466f09c53a21_1528724735774.jpeg"); //2、连接到这个资源 HTTP HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); InputStream is = urlConnection.getInputStream(); FileOutputStream fos = new FileOutputStream(new File("photo.png")); byte[] buffer = new byte[1024]; int len; while((len=is.read(buffer))!=-1){ fos.write(buffer,0,len); } fos.close(); is.close(); } }