如何使用以下网址下载文件:
我可以像这样用Url下载文件:
http://www.gradsch.ohio-state.edu/Depo/ETD_Tutorial/lesson2.pdf
使用此异步任务:
private class DownloadFilePDF extends AsyncTask<String, Integer, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
}
@Override
protected void onPostExecute (String result){
super.onPostExecute(result);
}
@Override
protected String doInBackground(String... sUrl) {
try {
Log.i("File download", "Started from :"+sUrl[0]);
URL url = new URL(sUrl[0]);
//URLConnection connection = url.openConnection();
File myDir = new File(Environment.getExternalStorageDirectory() + "/myDir");
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(sUrl[0]);
request.setHeader("User-Agent", sUrl[0]);
HttpResponse response = client.execute(request);
// create the directory if it doesnt exist
if (!myDir.exists()) myDir.mkdirs();
File outputFile = new File(myDir, "hotmail_contacts.pdf");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
int fileLength = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(outputFile);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
Log.i("File download", "complete");
} catch (Exception e) {
Log.e("File download", "error: " + e.getMessage());
}
return null;
}
}
但它不适用于第一个url,android显示此错误
11-27 13:50:26.360 9513-11482/com.example.ecollsandroidwebview E/File download﹕ error: