无法从保管箱下载文件

Can't download file from dropbox

我在保管箱中有一个 public 文件存储,现在我想使用 java 下载它。我是这样做的:

   String url = "http://www.dropbox.com/s/vk67dz9ca0oqz37/Chrysanthemum.jpg";
        String filename = "C:\Users\Public\Pictures\Sample Pictures\test.jpg";

        try {
            URL download = new URL(url);
            ReadableByteChannel rbc = Channels.newChannel(download.openStream());
            FileOutputStream fileOut = new FileOutputStream(filename);
            fileOut.getChannel().transferFrom(rbc, 0, 1 << 24);
            fileOut.flush();
            fileOut.close();
            rbc.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

但是test.jpg无效。怎么了?

当您在保管箱页面中单击 "Download original" 时,您可以看到它会将您重定向到 https://www.dropbox.com/s/vk67dz9ca0oqz37/Chrysanthemum.jpg?dl=1

因此,将 ?dl=1 附加到您的 url 并使用 https

String url = "https://www.dropbox.com/s/vk67dz9ca0oqz37/Chrysanthemum.jpg?dl=1";
String filename = "C:\Users\Public\Pictures\Sample Pictures\test.jpg";
try {
    URL download = new URL(url);
    ReadableByteChannel rbc = Channels.newChannel(download.openStream());
    FileOutputStream fileOut = new FileOutputStream(filename);
    fileOut.getChannel().transferFrom(rbc, 0, 1 << 24);
    fileOut.flush();
    fileOut.close();
    rbc.close();
} catch (Exception e) {
    e.printStackTrace();
}

或者,更短:

String url = "https://www.dropbox.com/s/vk67dz9ca0oqz37/Chrysanthemum.jpg?dl=1";
String filename = "C:\Users\Public\Pictures\Sample Pictures\test.jpg";
try {
    URL download = new URL(url);
    Path fileOut = new File(filename).toPath();
    Files.copy(download.openStream(), fileOut, StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
    e.printStackTrace();
}