本笔记来源于:尚硅谷Java零基础全套视频教程(宋红康2023版,java入门自学必备)
b站视频
统一资源定位符,对应着互联网的某一资源地址
2.URL的5个基本结构:
3.如何实例化:
URL url = new URL(“http://localhost:8080/examples/beauty.jpg?username=Tom");
4.常用方法:

5.可以读取、下载对应的url资源:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| public static void main(String[] args) {
HttpURLConnection urlConnection = null; InputStream is = null; FileOutputStream fos = null; try { URL url = new URL("http://localhost:8080/examples/beauty.jpg");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
is = urlConnection.getInputStream(); fos = new FileOutputStream("day10\\beauty3.jpg");
byte[] buffer = new byte[1024]; int len; while((len = is.read(buffer)) != -1){ fos.write(buffer,0,len); }
System.out.println("下载完成"); } catch (IOException e) { e.printStackTrace(); } finally { if(is != null){ try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if(fos != null){ try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } if(urlConnection != null){ urlConnection.disconnect(); } } }
|