【问题标题】:save file from url in android从android中的url保存文件
【发布时间】:2011-07-05 11:33:59
【问题描述】:

当我运行此 URL 并尝试将 t\in 保存为 .mp4 格式时,它会给出 FileNotFound 异常。 如果我从浏览器尝试相同的 URL,以 .mp4 格式存储 http://vimeo.com/moogaloop/play/clip:7926539/5cd4f7989ee0cb5018c131260aa1fc8c/1309860388/

这是我的代码:

String storage = Environment.getExternalStorageState();
    Log.i("System out", "" + storage);
    File rootsd = Environment.getExternalStorageDirectory();
    Log.d("ROOT PATH", "" + rootsd.getAbsolutePath());

    File mydir = new File(rootsd.toString() + "/unplugger");
    Log.i("DIR PATH", "" + mydir.getAbsolutePath());
    mydir.mkdir();

    URL u;
    try {
        u = new URL(
                "http://vimeo.com/moogaloop/play/clip:7926539/5cd4f7989ee0cb5018c131260aa1fc8c/1309860388/");

        HttpURLConnection c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setDoOutput(true);

        c.connect();

        FileOutputStream f = new FileOutputStream(new File(mydir + "/"
                + "myVideo.mp4"));

        InputStream in = c.getInputStream();

        byte[] buffer = new byte[1024];
        int len1 = 0;
        while ((len1 = in.read(buffer)) > 0) {
            f.write(buffer, 0, len1);
        }
        f.close();
        c.disconnect();
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Log.i("System out","malformed :"+e.getMessage());
        Log.i("System out","malformed :"+e.toString());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Log.i("System out","io: "+e.getMessage());
        Log.i("System out","io: "+e.toString());
    }

提前致谢。

【问题讨论】:

标签: android video vimeo


【解决方案1】:

改变这块:

new File(mydir + "/" + "myVideo.mp4")

改为:

new File(mydir, "myVideo.mp4")

【讨论】:

  • 其实问题是从url获取数据(filenotfound异常在这一行:InputStream in = c.getInputStream();)
  • 我认为 HttpURLConnection 不会自动处理重定向。由于您的链接不直接指向文件本身,您可能会收到 3xx HTTP 响应。这将是一个重定向并且不包含任何内容,因此如果您尝试获取内容,则会抛出FileNotFound。我建议使用 Android 上提供的 Apache 的 HttpClient 库。不要使用 HttpURLConnection。
猜你喜欢
  • 1970-01-01
  • 2021-02-17
  • 1970-01-01
  • 1970-01-01
  • 2013-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多