无法从 URL Java 获取特定图像
Cannot get a certain Image from a URL Java
我正在 Android Studio 中开发一个应用程序,该应用程序使用来自此 URL https://orteil.dashnet.org/cookieclicker/img
的图像
此目录中的所有图像都有效,除了这张图像:https://orteil.dashnet.org/cookieclicker/img/buildings.png
这张图片的奇怪之处在于,如果我将它保存在可绘制文件夹中,它会很好地加载这张图片。当我 运行 它时,InputStream 行抛出“java.net.ProtocolException:后续请求过多:21”。这是我无法从目录加载的唯一图像。有人可以解释为什么 InputStream 会为此图像抛出 ProtocolException 吗?
这是我 运行ning 的代码。请注意,此代码 运行s 在新线程
上
//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();
}
为什么要使用流连接进行图像加载....您可以获得更好的性能并在 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) {}
});
}
我发现 URL 实际上有特定图像的多个副本。所以代码会 ping 所有图像,直到达到 21 个请求上限。我修复它的方法是添加参数 v=7。这指定了我想要的副本,现在可以使用了。希望如果其他人遇到这个问题,这种解决方案可以解决它。
我正在 Android Studio 中开发一个应用程序,该应用程序使用来自此 URL https://orteil.dashnet.org/cookieclicker/img
的图像此目录中的所有图像都有效,除了这张图像:https://orteil.dashnet.org/cookieclicker/img/buildings.png
这张图片的奇怪之处在于,如果我将它保存在可绘制文件夹中,它会很好地加载这张图片。当我 运行 它时,InputStream 行抛出“java.net.ProtocolException:后续请求过多:21”。这是我无法从目录加载的唯一图像。有人可以解释为什么 InputStream 会为此图像抛出 ProtocolException 吗?
这是我 运行ning 的代码。请注意,此代码 运行s 在新线程
上//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();
}
为什么要使用流连接进行图像加载....您可以获得更好的性能并在 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) {}
});
}
我发现 URL 实际上有特定图像的多个副本。所以代码会 ping 所有图像,直到达到 21 个请求上限。我修复它的方法是添加参数 v=7。这指定了我想要的副本,现在可以使用了。希望如果其他人遇到这个问题,这种解决方案可以解决它。