图片下载不全

问题描述

我想下载此图片 https://ntnuspansk.files.wordpress.com/2016/04/2447301.jpg,但只下载了 8 个,共 44,0 KB。不会抛出任何异常。我用其他页面图片测试了代码并工作,问题特别是这张图片

    public static void main(String[] args) throws MalformedURLException {
        URL url = new URL("https://ntnuspansk.files.wordpress.com/2016/04/2447301.jpg");

        try (FileOutputStream outputStream = new FileOutputStream(new File("C:\\Users\\caslopden\\Desktop\\galicia.jpg"));
                InputStream inputStream = url.openStream()) {
            byte[] bytes = new byte[2048];
            int numBytesRead;
            while ((numBytesRead = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes,numBytesRead);
            }
        } catch (Exception e) {
            e.printstacktrace();
        }
    }

解决方法

服务器根据 //escape HTML $htmlEscapedPattern = htmlspecialchars('<nav><a>something</a></nav>'); //escape slashes $forwardSlashEscapedPattern = str_replace("/","\/",$htmlEscapedPattern); //wrap as regex pattern $pattern = "/" . $forwardSlashEscapedPattern . "/i"; 标头返回不同的内容。因为您没有设置,所以使用了一些默认值,服务器将其解释为您要下载 HTML。您最终下载的不是部分图像,而是 HTML 文档。

要解决此问题,您需要设置 Accept 标头以请求图像。您可以通过在某些开发人员工具中检查请求来查看标头浏览器设置。我使用了 Accept

这是您的代码的修改版本(我还制作了 URL 和输出字段参数以便于测试):

"image/png,image/*;q=0.8,*/*;q=0.5"

我测试并成功下载了(完整的)JPEG 图像。

,

使用这个:

public static void downloadWithJavaIO(String url,String localFilename) {

        try (BufferedInputStream in = new BufferedInputStream(new URL(url).openStream()); FileOutputStream fileOutputStream = new FileOutputStream(localFilename)) {

            byte dataBuffer[] = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(dataBuffer,1024)) != -1) {
                fileOutputStream.write(dataBuffer,bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }