检查来自 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
类型:
- 直接link。例如:https://dl-ssl.google.com/android/repository/android-14_r04.zip。从这个 link,我们可以直接下载数据并获取文件名,包括文件扩展名(在这个 link,
.zip
扩展名中)。这样我们就可以知道要下载什么文件了。你可以尝试从link. 下载
- 不直接 link。例如:http://www.example.com/directory/download?file=52378。您是否尝试过从 Google 云端硬盘下载数据?当从Google Drive下载数据时,它会给你一个间接的link,比如上面的link。我们永远不知道 link 是否包含文件或网页。另外,我们不知道文件名和文件扩展名是什么,因为这个 link 类型不明确且随机。
我要检查是文件还是网页。如果内容类型是文件,我必须下载它。
所以我的问题是:
- 如何检查非直接 link 的内容类型?
- 如本题评论所示,HTTP-redirects能解决问题吗?
感谢您的帮助。
此类链接使用 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-dosexec
或 application/x-rar
.
MimeTypeMap.getFileExtensionFromUrl(url)
这个对我有用,你必须使用改造来检查 header 的响应。首先,您必须定义一个端点以使用要检查的 url 调用它:
@GET
suspend fun getContentType(@Url url: String): Response<Unit>
然后你这样调用得到内容类型header:
api.getContentType(url).headers()["content-type"]
我问这个
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
类型:
- 直接link。例如:https://dl-ssl.google.com/android/repository/android-14_r04.zip。从这个 link,我们可以直接下载数据并获取文件名,包括文件扩展名(在这个 link,
.zip
扩展名中)。这样我们就可以知道要下载什么文件了。你可以尝试从link. 下载
- 不直接 link。例如:http://www.example.com/directory/download?file=52378。您是否尝试过从 Google 云端硬盘下载数据?当从Google Drive下载数据时,它会给你一个间接的link,比如上面的link。我们永远不知道 link 是否包含文件或网页。另外,我们不知道文件名和文件扩展名是什么,因为这个 link 类型不明确且随机。
我要检查是文件还是网页。如果内容类型是文件,我必须下载它。
所以我的问题是:
- 如何检查非直接 link 的内容类型?
- 如本题评论所示,HTTP-redirects能解决问题吗?
感谢您的帮助。
此类链接使用 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-dosexec
或 application/x-rar
.
MimeTypeMap.getFileExtensionFromUrl(url)
这个对我有用,你必须使用改造来检查 header 的响应。首先,您必须定义一个端点以使用要检查的 url 调用它:
@GET
suspend fun getContentType(@Url url: String): Response<Unit>
然后你这样调用得到内容类型header:
api.getContentType(url).headers()["content-type"]