FileNotFoundException:添付ファイルをダウンロード
WebViewでメールの添付ファイルをダウンロードしたいのですが、FileNotFoundExceptionのエラーが出ます。
ちなみにテストはoutlookでしています。
コード:
ImageGetTask.java
InputStream is;
String url = "https://example.com";
try {
URL u = new URL(url);
HttpURLConnection con = (HttpURLConnection) u.openConnection();
con.setRequestMethod("GET");
con.setDoOutput(true);
con.connect();
int responseCode = con.getResponseCode();
if (responseCode >= 400 && responseCode <= 499) {
}else{
is = con.getInputStream();
String path = Environment.getExternalStorageDirectory() + "/apdroid/";
String fileName = url.substring(url.lastIndexOf('/') + 1);
File dir = new File(path);
dir.mkdirs();
File outputFile = new File(dir, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fos.close();
is.close();
image = BitmapFactory.decodeStream(is);
}
return image;
}catch (IOException e) {
e.printStackTrace();
}
こちらのコードに変更してやってみたらダウンロードはできるのですが、画像形式ではなくてHtmlで保存されてしまします。
Request request = new Request(Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "download");
request.setVisibleInDownloadsUi(false);
request.setDescription(contentDisposition);
downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
query = new DownloadManager.Query();
// ダウンロードフラグ
query.setFilterByStatus(DownloadManager.STATUS_FAILED);
query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL);
downloadid = downloadManager.enqueue(request);
receiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
Log.d("xxx", "End Download download Id = " + id);
query.setFilterById(id);
Cursor c = downloadManager.query(query);
if(c.moveToFirst()) {
int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
int reason = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_REASON));
Log.d("status", Integer.toString(status));
Log.d("reason", Integer.toString(reason));
// ダウンロードに失敗した場合
if (status == DownloadManager.STATUS_FAILED) {
downloadManager.remove(downloadid);
// ダウンロードに成功した場合
} else if (status == DownloadManager.STATUS_SUCCESSFUL) {
Log.d("","SECCUSS");
try {
ParcelFileDescriptor file =
downloadManager.openDownloadedFile(downloadid);
FileInputStream files =
new ParcelFileDescriptor.AutoCloseInputStream(file);
imageView.setImageBitmap(BitmapFactory.decodeStream(files));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
c.close();
}
}
};
registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));