Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get full video download from a link?

Tags:

java

I am trying to download a video from a link, but it only downloads a small part of it, so it can't be watched at all. How would you download an entire video no matter how large the file is from a link?

    try {
        URL url;
        byte[] buf;
        int byteRead, byteWritten = 0;
        url = new URL(fAddress);
        outStream = new BufferedOutputStream(new FileOutputStream(destinationDir + "\\" + localFileName));

        conn = url.openConnection();
        is = conn.getInputStream();
        buf = new byte[size];
        while ((byteRead = is.read(buf)) != -1) {
            outStream.write(buf, 0, byteRead);
            byteWritten += byteRead;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
            outStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
like image 358
J. Doe Avatar asked Oct 15 '25 03:10

J. Doe


1 Answers

It looks like server may redirect you to other location which your code doesn't handle. To get final location you can try method like (based on: http://www.mkyong.com/java/java-httpurlconnection-follow-redirect-example/):

public static String getFinalLocation(String address) throws IOException{
    URL url = new URL(address);
    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    int status = conn.getResponseCode();
    if (status != HttpURLConnection.HTTP_OK) 
    {
        if (status == HttpURLConnection.HTTP_MOVED_TEMP
            || status == HttpURLConnection.HTTP_MOVED_PERM
            || status == HttpURLConnection.HTTP_SEE_OTHER)
        {
            String newLocation = conn.getHeaderField("Location");
            return getFinalLocation(newLocation);
        }
    }
    return address;
}

Now you simply need to change

url = new URL(fAddress);

to

url = new URL(getFinalLocation(fAddress));
like image 141
Pshemo Avatar answered Oct 16 '25 16:10

Pshemo