如何从链接获得完整的视频下载?

时间:2016-02-05 22:35:54

标签: java

我正在尝试从链接下载视频,但它只下载了一小部分视频,因此根本无法观看。无论文件来自链接的大小,您如何下载整个视频?

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

1 个答案:

答案 0 :(得分:4)

看起来服务器可能会将您重定向到您的代码无法处理的其他位置。要获得最终位置,您可以尝试类似方法(基于: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;
}

现在你只需要改变

url = new URL(fAddress);

url = new URL(getFinalLocation(fAddress));