我正在尝试使用Android从URL中找到文件大小,但我得到的是getContentLength(): - 1,但如果我将在任何浏览器中打开该网址,那么浏览器可以计算文件大小,在哪里作为浏览器也是客户端应用程序。
MyCode:
try {
URL url = new URL("https://www.dropbox.com/s/mk75lhvi96gkc00/match.flv?dl=0");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
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();
//fileLength : -1;
} 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();
}
这是我上面的android代码,我得到-1作为文件长度,但浏览器可以很容易地计算相同的URL文件大小。
请建议我解决一下。
答案 0 :(得分:1)
此代码适用于我:
public int getFileSizeFromURL(String urlPath) {
int fileSize = 0;
try {
URL url = new URL(urlPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
fileSize = connection.getContentLength();
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return fileSize;
}
的代码
答案 1 :(得分:1)
尝试从
更改链接"https://www.dropbox.com/s/mk75lhvi96gkc00/match.flv?dl=0"
到
"https://www.dropbox.com/s/mk75lhvi96gkc00/match.flv?dl=1"