文件我有一個網址https://www.youtube.com/watch?v=mGhQTs3F1O4&spf=prefetch,當我在它下載包含視頻的信息文件瀏覽器中打開..網址下載android系統
在瀏覽器中效果很好,但我不能說實現在Android的..當我嘗試使用下面的代碼我得到的html文件,下載文件..
private class DownloadTask extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
String path = Environment.getExternalStorageDirectory().getPath()
+ "/" + sUrl[1];
Log.d(TAG, "PATH: " + path);
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP "
+ connection.getResponseCode() + " "
+ connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream(path);
byte data[] = new byte[4096];
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return path;
}
}
所以..任何想法?
嘗試設置在請求的MIME類型。 – avinash