在Android中使用HttpURLConnection时出现apk文件的FileNotFoundException问题

5
            URL url = new URL(arg0[1]);
            HttpURLConnection c = (HttpURLConnection) url.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();

            String PATH = "/mnt/sdcard/Android/";
            File file = new File(PATH);
            file.mkdirs();
            File outputFile = new File(file, "myGame.apk");
            if(outputFile.exists()){
                outputFile.delete();
            }
            FileOutputStream fos = new FileOutputStream(outputFile);

            InputStream is = c.getInputStream();

            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len1);
            }
            fos.close();
            is.close();

            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(new File("mnt/sdcard/Android/myGame.apk")), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);

我想实现应用程序的自动更新功能,它将下载apk文件并安装。然而,当我通过Java下载时遇到了异常:java.io.FileNotFoundException http://192.168.2.143/myGame.apk,其中url [0] =“http://192.168.2.143/myGame.apk”,我使用设备中的浏览器打开http://192.168.2.143/myGame.apk,apk可以下载并在sdcard / Download /文件夹内。我的清单中有INTERNET权限。有什么想法吗?


你是在模拟器上测试吗? - Mr.Me
6
去掉c.setDoOutput(true)后再尝试。 - Brijesh Thakur
我在我的设备上运行,而不是模拟器。 - AkariKamigishi
1
移除 c.setDoOutput(true) 可以解决问题。谢谢。 - AkariKamigishi
@BrijeshThakur 谢谢,它起作用了。 - kiran boghra
它没有显示错误,但是它没有下载任何东西。@AkariKamigishi - c-an
1个回答

1
如Brijesh Thakur所说:
去掉c.setDoOutput(true)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接