1. URL:(Uniform Resource Locator) 统一资源定位符 他标识Internet上某一资源的地址
    2. URL的基本结构由5个部分组成

    传输协议://主机名称:端口号/文件名#片段名?参数列表
    例:https://yazhouse8.com/article.php?cate=1
    片段名: 锚点

    1. /**
    2. * @author:LYY 创建时间:2022/5/11
    3. */
    4. public class URLTest {
    5. /**
    6. * 下载资源
    7. * 从指定的url下载资源
    8. */
    9. @Test
    10. void test01() {
    11. FileOutputStream fileOutputStream = null;
    12. InputStream inputStream = null;
    13. HttpURLConnection urlConnection = null;
    14. try {
    15. // url对象 相当于在内存中记录的信息
    16. URL url = new URL("https://i.17173cdn.com/9ih5jd/YWxqaGBf/forum/202204/27/hFMSfNbqbuAcayq.gif");
    17. // 获取链接对象
    18. urlConnection = (HttpURLConnection) url.openConnection();
    19. // 打开链接
    20. urlConnection.connect();
    21. // 获取输入流
    22. inputStream = urlConnection.getInputStream();
    23. // 获取输出流 将文件保存到本地硬盘
    24. fileOutputStream = new FileOutputStream("hFMSfNbqbuAcayq.gif");
    25. byte[] bytes = new byte[1024];
    26. int len;
    27. while ((len = inputStream.read(bytes)) != -1) {
    28. fileOutputStream.write(bytes, 0, len);
    29. }
    30. } catch (MalformedURLException e) {
    31. e.printStackTrace();
    32. } catch (IOException e) {
    33. e.printStackTrace();
    34. } finally {
    35. // 释放资源
    36. if (fileOutputStream != null) {
    37. try {
    38. fileOutputStream.close();
    39. } catch (IOException e) {
    40. e.printStackTrace();
    41. }
    42. }
    43. if (inputStream != null) {
    44. try {
    45. inputStream.close();
    46. } catch (IOException e) {
    47. e.printStackTrace();
    48. }
    49. }
    50. if (urlConnection != null) {
    51. urlConnection.disconnect();
    52. }
    53. }
    54. }
    55. @Test
    56. void test() {
    57. try {
    58. URL url = new URL("https://yazhouse8.com/article.php?cate=1");
    59. // 输出url协议
    60. System.out.println(url.getProtocol());
    61. // 输出url ip
    62. System.out.println(url.getHost());
    63. // 输出url 端口号
    64. System.out.println(url.getPort());
    65. // 输出文件路径
    66. System.out.println(url.getPath());
    67. // 输出url查询条件
    68. System.out.println(url.getQuery());
    69. // 输出资源路径
    70. System.out.println(url.getFile());
    71. } catch (MalformedURLException e) {
    72. e.printStackTrace();
    73. }
    74. }
    75. }