下载的文件有0个字节

时间:2015-07-30 17:27:51

标签: java file download

我尝试将.mp3音乐文件从this URL下载到项目根目录,但下载的文件大小总是0字节(空白)。下载也会立即停止。

我使用以下代码:

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.io.FileUtils;

public class MusicDownloader
{
    public static void main(String[] arguments) throws MalformedURLException, IOException
    {
        download("https://www.youtube.com/audiolibrary_download?vid=d0a68933f592c297", "Ponies and Balloons");
    }

    public static void download(String url, String fileName) throws MalformedURLException, IOException
    {
        FileUtils.copyURLToFile(new URL(url), new File(fileName + ".mp3"));
    }
}

在浏览器中,手动下载文件可以正常运行。来自其他网站的下载链接,例如this one没有问题需要由代码处理。这可能是什么问题?

Sending a valid user-agent String也无效。

2 个答案:

答案 0 :(得分:4)

问题实际上在于您的网址https://www.youtube.com/audiolibrary_download?vid=d0a68933f592c297。它实际上是以资源温度移动 - 301 状态代码发出重定向。所以你需要选择新的URL。我尝试使用HttpURLConnection来查看新重定向的网址是https://youtube-audio-library.storage.googleapis.com/d0a68933f592c297。您可以使用以下代码: -

String urlString = "https://www.youtube.com/audiolibrary_download?vid=d0a68933f592c297";
        URL url = new URL(urlString);
        HttpURLConnection huc = (HttpURLConnection)url.openConnection();
        int statusCode = huc.getResponseCode(); //get response code
        if (statusCode == HttpURLConnection.HTTP_MOVED_TEMP
                || statusCode == HttpURLConnection.HTTP_MOVED_PERM){ // if file is moved, then pick new URL
            urlString = huc.getHeaderField("Location");
            url = new URL(urlString);
            huc = (HttpURLConnection)url.openConnection();
        }
        System.out.println(urlString);  
        InputStream is = huc.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        FileOutputStream fos = new FileOutputStream("test.mp3");
        int i = 0;
        while ((i = bis.read()) != -1)
            fos.write(i);

您可以检查FileUtils或不同的效果。我相信,它应该是。干杯:)

答案 1 :(得分:-3)

因为它是违法的并且针对Youtube Terms of Service

Youtube专门阻止了从其网站下载mp3的大多数通用方法。简单的10行代码不会起作用或盗版会比现在更大。

如果他们抓住你,你被阻止

相关问题