首页 > 解决方案 > 无法从 URL Java 获取特定图像

问题描述

我正在使用来自此 URL https://orteil.dashnet.org/cookieclicker/img的图像的 Android Studio 中的应用程序


此目录中的所有图片都可以使用,除了这张图片:https ://orteil.dashnet.org/cookieclicker/img/buildings.png

这张图片的奇怪之处在于,如果我将它保存在可绘制文件夹中,它会很好地加载这张图片。当我运行它时,InputStream 行抛出“java.net.ProtocolException: Too many follow-up requests: 21”。这是我无法从目录加载的唯一图像。有人可以解释为什么 InputStream 会为此图像抛出 ProtocolException 吗?

这是我正在运行的代码。注意-此代码在新线程上运行

//src is the  bad url as a string
//myBitmap is a Bitmap array
try {
    URL url = new URL(src);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    InputStream input = connection.getInputStream();
    myBitmap[0] = BitmapFactory.decodeStream(input);

} catch ( IOException e) {
   e.printStackTrace();
}

标签: javaandroidimagehttpurlconnectionandroid-bitmap

解决方案


为什么你使用流连接来加载图像......你可以在Glide中获得更好的性能并处理此类连接问题

如果您不想使用 URL 中的位图,请使用:

GlideApp.with(itemView.getContext())
        .asBitmap()
        .load(imageUrl)  //https://orteil.dashnet.org/cookieclicker/img/buildings.png
        .into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {}
            });
        }

推荐阅读