gpt4 book ai didi

android - 检查url是否为有扩展名限制的图片

转载 作者:行者123 更新时间:2023-11-29 14:58:24 24 4
gpt4 key购买 nike

如何检查 URL 是否为必须为 PNG、GIF、JPG 格式的图像 URL

我看到可以用这段代码来完成:

URLConnection connection = new URL("http://foo.bar/w23afv").openConnection();
String contentType = connection.getHeaderField("Content-Type");
boolean image = contentType.startsWith("image/");

但是,我需要使用 GlideOKHttpClient 进行检查。

如何使用上述两种技术实现这一点?

最佳答案

如果您只想检查 URL 的 Content-Type,而不实际下载内容,则 HTTP HEAD request将是合适的。

The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification.

您可以使用 OkHttp 执行此操作,如下所示:

OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder()
.url("http://foo.bar/w23afv")
.head()
.build();

try {
Response response = client.newCall(request).execute();
String contentType = response.header("Content-Type");
boolean image = false;
if (contentType != null) {
image = contentType.startsWith("image/");
}

} catch (IOException e) {
// handle error
}

关于android - 检查url是否为有扩展名限制的图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55104896/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com