我正在使用下面的代码下载文件。然而,我只想在远程文件比本地存储的文件更新时(如果有的话)才进行下载。我能否以某种方式使用 if-modefied-since HTTP 标头?如何更新我的代码来实现这个目标?
有没有关于如何实际测试这个的好主意?如果文件不是更新的,那么while循环就不应该运行,对吗?
private class DownloadFile extends AsyncTask<String, Integer, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
@Override
protected String doInBackground(String... sUrl) {
try {
URL url = new URL(sUrl[0]);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a typical 0-100% progress bar
int fileLength = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(path);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
}
catch(MalformedURLException e)
{
e.printStackTrace();
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
mProgressDialog.dismiss();
// TODO: here file is downloaded and we are ready to process it.
}
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mProgressDialog.setProgress(progress[0]);
}
}
我已更新我的代码,看起来像这样...
@Override
protected String doInBackground(String... sUrl) {
long lastModified = new File(path).lastModified();
try
{
URL url = new URL(sUrl[0]);
URLConnection connection = url.openConnection();
connection.connect();
if(lastModified != 0)
{
connection.setIfModifiedSince(lastModified);
}
// this will be useful so that you can show a typical 0-100% progress bar
int fileLength = connection.getContentLength();
...
有没有关于如何实际测试这个的好主意?如果文件不是更新的,那么while循环就不应该运行,对吗?