【问题标题】:Android FileNotFound Exception - Cannot getInputStream from image URL that does not have file formatAndroid FileNotFound 异常 - 无法从没有文件格式的图像 URL 获取输入流
【发布时间】:2010-11-18 19:39:17
【问题描述】:

标题很清楚。

以下代码...:

    URL imageUrl = new URL(url);
   try {
                HttpURLConnection conn= (HttpURLConnection)imageUrl.openConnection();
                conn.setDoInput(true);
                conn.connect();
                int length = conn.getContentLength();
                InputStream is = conn.getInputStream();
                return BitmapFactory.decodeStream(is);
           } catch (IOException e) {
            e.printStackTrace();
           }

如果 url 不包含文件格式将失败。例如,某些由 google 托管的图像会显示图像,但在 url 中没有文件格式(.png、.jpg 等)。

因此,url 连接的 content-type 标头返回“text/html”。我相信这是问题所在。

我尝试设置一个新的内容类型标头,但这似乎没有任何改变。

有人知道解决方法吗?

谢谢。

【问题讨论】:

  • 你能举一个失败的例子吗?

标签: java android image httpurlconnection filenotfoundexception


【解决方案1】:

我遇到了问题,我记得用谷歌搜索,这是我的最终解决方案

        try {
            URL url = new URL(imageUrl);
            HttpGet httpRequest = null;

            httpRequest = new HttpGet(url.toURI());

            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);

            HttpEntity entity = response.getEntity();
            BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
            InputStream input = bufHttpEntity.getContent();

            Bitmap bitmap = BitmapFactory.decodeStream(input);

            ImageActivity.this.i.setImageBitmap(bitmap);
            ImageActivity.this.i.refreshDrawableState();
            input.close();

        } catch (MalformedURLException e) {
            Log.e("ImageActivity", "bad url", e);
        } catch (Exception e) {
            Log.e("ImageActivity", "io error", e);
        }

【讨论】:

  • 这是解决方法!谢谢亚伦!我想修复工作是因为使用了 Apache 的 HttpGet、HttpClient、HttpResponse 和 HttpEntity 对象。这些取代了 HttpUrlConnection 对象,并且显然可以更好地处理一些事情。我对 BufferedHttpEntity 不是很熟悉,但这也可能与它有很大关系。
【解决方案2】:

BitmapFactory.decodeStream 只读取图像本身的原始字节流,它不知道 URL 和内容编码,所以我认为他们没有错。应该可以直接从图片头读取图片格式。

可能 URL 被重定向了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-02
    相关资源
    最近更新 更多