我正在尝试在Android上为我的应用程序实现简单的下载管理器,我使用简单的Serivce
从Internet下载文件,当我使用此方法创建连接时:
private HttpURLConnection createConnection(String urlStr) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setReadTimeout(timeout);
conn.setConnectTimeout(timeout);
return conn;
}
我没有得到任何例外,并且可以正常使用此链接:
https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png
现在我想从连接中获取getInputStream()
并将变量指定为:
in = new BufferedInputStream(connection.getInputStream(),BUFFER_SIZE);
但是我收到了这个错误:
'java.io.FileNotFoundException' exception.
我可以从连接中获得文件长度,但我无法下载
new Thread(new Runnable() {
@Override
public void run() {
try {
prepareDownload(fileUrl, filePath, lastModified);
connection = createConnection(fileUrl);
fileDownloadStatus = downloadStatus.DOWNLOADING;
if (!startNewDownload) {
connection.setRequestProperty("Range", "bytes=" + downloadedFile.length() + "-");
}
if (onDownloadProcess != null)
onDownloadProcess.fileLength(fileLength);
in = new BufferedInputStream(connection.getInputStream(), BUFFER_SIZE);
long progressLength = 0;
if (!startNewDownload) {
progressLength += downloadedFile.length();
// append to exist downloadedFile
writer = new FileOutputStream(filePath, true);
} else {
writer = new FileOutputStream(filePath);
// save remote last modified data to local
lastModified = connection.getHeaderField("Last-Modified");
}
try {
byte[] buffer = new byte[BUFFER_SIZE];
int count;
while (getFileDownloadStatus() == downloadStatus.DOWNLOADING && (count = in.read(buffer)) != -1) {
progressLength += count;
writer.write(buffer, 0, count);
// progress....
if (onDownloadProcess != null)
onDownloadProcess.onProgress((int) (progressLength * 100 / fileLength));
if (progressLength == fileLength) {
progressLength = 0;
setFileDownloadStatus(downloadStatus.COMPLETE);
}
}
...
}).start();
答案 0 :(得分:0)
首先,我看到您使用HttpConnection作为https
网址。
如果请求失败(无法找到指定的文件),您将收到FileNotFound。很可能是因为这个原因。
以下是我在我的应用中使用的WebRequest类的片段,它适用于所有https下载
URL url = new URL(request);
con = (HttpsURLConnection)url.openConnection();
con.setDoOutput(true);
con.setInstanceFollowRedirects(false);
con.setRequestProperty("charset", "utf-8");
con.setUseCaches(false);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.write(postData);
wr.flush();
wr.close();
// those are from my class to return the server response
result.setResultCode(con.getResponseCode());
result.setResultMessage(con.getResponseMessage());
InputStream stream = con.getInputStream();
InputStreamReader reader = new InputStreamReader(stream);
BufferedReader br = new BufferedReader(reader);
这是针对html请求(直到文本末尾阅读),但我认为您也可以使用我在con
上设置的属性进行图像下载。