12 URL 下载网络资源
Uniform Resource Locator:统一资源定位符; 统一资源定位器; 资源定位器; 资源定位; 源定位符;
package Internet;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
// 对比多线程时学的下载网图
public class Test12_URLlDownload {
public static void main(String[] args) throws Exception {
// 获得URL:统一资源定位器 下载地址
URL url = new URL("https://pic.netbian.com/uploads/allimg/171009/194751-15075496719aaa.jpg");
System.out.println(url.getProtocol()); // 协议
System.out.println(url.getHost()); // 主机IP
System.out.println(url.getPort()); // 端口,这里没有?
System.out.println(url.getAuthority()); // 作者
System.out.println(url.getFile()); // 文件全路径
System.out.println(url.getPath()); // 文件
// 连接这个资源
HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
// 下载
InputStream is = httpURLConnection.getInputStream();
FileOutputStream fos = new FileOutputStream("the witcher 3.jpg");
byte[] buffer = new byte[1];
while (is.read(buffer)!=-1){
fos.write(buffer,0,buffer.length);
}
}
}