URL下载网络资源
https://www.baidu.com/
-
统一资源定位符:定位资源的,定位互联网上的某一个资源。
协议://IP地址:端口/项目名/资源
/**
* URL:方法
*/
public class URLDemo_01 {
public static void main(String[] args) throws MalformedURLException {
URL url = new URL("https//localhost:8080/helloWorld/index.jpg?username=ym&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()); // 参数
}
}
public class URLDown {
public static void main(String[] args) throws IOException {
// 1、下载地址
URL url = new URL("网络资源地址");
// 2、连接到这个资源
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fos = new FileOutputStream("server.jpg");
byte[] bytes = new byte[1024];
int len;
while ((len = inputStream.read(bytes))!= -1 ){
fos.write(bytes,0,len); // 写出这个数据
}
fos.close();
inputStream.close();
urlConnection.connect();// 断开连接
}
}