The downloaded file is 0 bytes

I am trying to download a music file .mp3

from this URL to the project root, but the downloaded file is always 0 bytes in size (empty). The download also stops immediately.

I am using the following code:

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"));
    }
}

      

In the browser, downloading the file manually works flawlessly. Link to download from another website eg. this one had no problem to handle with code. What could be the problem here?

Sending a valid String user agent also doesn't work.

+3


source to share


2 answers


The problem is with your url https://www.youtube.com/audiolibrary_download?vid=d0a68933f592c297

. In fact, it issues the redirect as Temp Moved - 301 . Therefore, you need to choose a new one URL

. I tried using it HttpURLConnection

to see what the new redirected url is https://youtube-audio-library.storage.googleapis.com/d0a68933f592c297

. You can use the below code: -

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);

      



The same effect you can check is available in FileUtils

or not. I'm sure it should be. Cheers :)

+3


source


Because it is illegal and against Youtube Terms of Service

Youtube specifically blocks the most common ways to download mp3 from their site. Simple 10-line lines of code won't work or piracy would be more than it already is.



If they catch you, you WILL be blocked

-3


source







All Articles