检查来自 URL 的内容类型

Checking content type from URL

我问这个 before and Evgeniy Dorofeev 回答了。虽然只为直接 link 工作,但我接受了他的回答。他刚刚告诉我直接从 link:

检查内容类型
String requestUrl = "https://dl-ssl.google.com/android/repository/android-14_r04.zip";
URL url = new URL(requestUrl);
URLConnection c = url.openConnection();
String contentType = c.getContentType();

据我所知,下载文件有两种URL类型:

我要检查是文件还是网页。如果内容类型是文件,我必须下载它。

所以我的问题是:

感谢您的帮助。

此类链接使用 HTTP redirects. To get the correct content type, all you have to do is tell HttpURLConnection to follow the redirects by setting setFollowRedirects() to true (documented here).

将浏览器重定向到实际内容

打开 URLConnection 后,会返回一个头文件。里面有一些关于这个文件的信息。你可以从那里拉你想要的东西。例如:

URLConnection u = url.openConnection();
long length = Long.parseLong(u.getHeaderField("Content-Length"));
String type = u.getHeaderField("Content-Type");

length 是以字节为单位的文件大小,type 类似于 application/x-dosexecapplication/x-rar.

MimeTypeMap.getFileExtensionFromUrl(url)

这个对我有用,你必须使用改造来检查 header 的响应。首先,您必须定义一个端点以使用要检查的 url 调用它:

@GET
suspend fun getContentType(@Url url: String): Response<Unit>

然后你这样调用得到内容类型header:

api.getContentType(url).headers()["content-type"]