1.URL(Uniform Resource Locator)的理解:

  • 统一资源定位符,对应着互联网的某一资源地址

2.URL的5个基本结构:

4.常用方法:

image.png

5.可以读取、下载对应的url资源:

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