Android FileNotFoundexception – 无法从没有文件格式的图像URL获取getInputStream

标题非常自我解释。

以下代码……:

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不包含文件格式,则会失败。 例如,谷歌托管的一些图像将显示图像,但不具有文件格式(.png,.jpg等)作为url的一部分。

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

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

有人知道解决方法吗?

谢谢。

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

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

BitmapFactory.decodeStream只读取图像本身的原始字节流,它不知道URL和内容编码,所以我不认为它们在这里有问题。 它应该能够直接从图像标题中读取图像格式。

可能会重定向URL。