Android FileNotFound异常 - 无法从没有文件格式的图像URL获取getInputStream

rel*_*iks 3 java android image filenotfoundexception httpurlconnection

标题非常自我解释.

以下代码......:

    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();
           }
Run Code Online (Sandbox Code Playgroud)

如果url不包含文件格式,则会失败.例如,谷歌托管的一些图像将显示图像,但不具有文件格式(.png,.jpg等)作为网址的一部分.

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

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

有人知道解决方法吗?

谢谢.

Aar*_*ers 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);
        }
Run Code Online (Sandbox Code Playgroud)