java通过http网络url下载文件

    @Test
    public void test3() throws ParseException {
        String fileUrl = "http://*****/123.pdf";
        String savePath = "C:\\Users\\HHH\\Desktop\\文件\\123.pdf";

        try {
            URL url = new URL(fileUrl);
            InputStream inputStream = url.openStream();

            Path outputPath = Path.of(savePath);
            Files.copy(inputStream, outputPath, StandardCopyOption.REPLACE_EXISTING);

            System.out.println("File downloaded successfully.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

上面代码报错,修改URL url = new URL(fileUrl);,使用URL url = new URL(new URI(fileUrl).toASCIIString());

    @Test
    public void test3() throws ParseException {
        String fileUrl = "http://*****/123.pdf";
        String savePath = "C:\\Users\\HHH\\Desktop\\文件\\123.pdf";

        try {
            URL url = new URL(new URI(fileUrl).toASCIIString());
            InputStream inputStream = url.openStream();

            Path outputPath = Path.of(savePath);
            Files.copy(inputStream, outputPath, StandardCopyOption.REPLACE_EXISTING);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

原因:

URL url = new URL(fileUrl); 和 URL url = new URL(new URI(fileUrl).toASCIIString()); 之间有一些微小的区别。
URL url = new URL(fileUrl);:这种方式直接使用 URL 类的构造函数创建一个 URL 对象。它假设 fileUrl 是一个合法的 URL 字符串,并不对其进行任何修改或编码。如果 fileUrl 含有特殊字符或非法字符,可能会导致 MalformedURLException 异常。
URL url = new URL(new URI(fileUrl).toASCIIString());:这种方式先通过 URI 类创建一个 URI 对象,然后再将其转换为 ASCII 字符串,最后使用 URL 类的构造函数创建一个 URL 对象。这种方式会对 fileUrl 进行编码,将其中的非 ASCII 字符转换为 ASCII 编码形式。这可以确保 URL 字符串的合法性。例如,使用这种方式可以正确处理包含中文或特殊字符的 URL。
总而言之,URL url = new URL(fileUrl); 直接创建 URL 对象,不对 URL 字符串进行编码。而 URL url = new URL(new URI(fileUrl).toASCIIString()); 先通过 URI 对象将 URL 字符串编码为 ASCII 形式,然后再创建 URL 对象。使用这种方式可以确保 URL 的合法性,尤其是处理包含非 ASCII 字符的 URL。

你可能感兴趣的:(java,java)