Android文件未找到异常 - 无法从没有文件格式的图片URL获取InputStream

3
标题已经很明确了。
以下代码...:
    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连接的内容类型标头返回“text/html”。我认为这是问题所在。

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

有人知道解决方法吗?

谢谢。


你能给一个失败的URL示例吗? - robert_x44
2个回答

7

我遇到了问题,想起在网上搜索后,找到了这个最终解决方案。

        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);
        }

这就是解决方法!谢谢Aaron!我想修复的原因是利用了Apache的HttpGet、HttpClient、HttpResponse和HttpEntity对象。它们取代了HttpUrlConnection对象,并且显然处理某些事情更好。我对BufferedHttpEntity不是特别熟悉,但那可能也有很大关系。 - reliks

0

BitmapFactory.decodeStream只会读取图像本身的原始字节流,它对URL和内容编码没有任何了解,所以我不认为它们有问题。它应该可以直接从图像头部读取图像格式。

可能是URL被重定向了。


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