获取 Url 链接的文件类型有三种方法(前两种不准确,推荐第三种):
- 通过 url 后缀名获取,这种不用说,直接是静态文件链接还好说,但其它很多情况获取不准确,因为很多资源都是通过请求获取的,像http://www.baidu.com/,实际对应的 Html,行不通;
- 通过文件流的前面几个字节来判断类型获取:
String extension = HttpURLConnection.guessContentTypeFromStream(inputStream);
但很多情况也识别不出来。 - 最后一种比较准确。即用 ContentType 获取文件后缀名,代码如下:
// response 为获取的 url 响应
String value = response.getEntity().getContentType().getValue();
MimeTypes allTypes = MimeTypes.getDefaultMimeTypes();
MimeType mimeType = allTypes.forName(value);
String extension = mimeType.getExtension();
MimeTypes 和 MimeType 是下面的类库中的类。
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-core</artifactId>
<version>1.22</version>
</dependency>
上诉response对象是来自于Apache HttpClient库中的HttpResponse类
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>