有個地方要用到url地址轉(zhuǎn)換為文件,但是url的地址不能得出明確的后綴格式,于是使用了URLConnection的方法。
URLConnection的方法里有兩個方法:
- guessContentTypeFromName
- guessContentTypeFromStream
第一個是根據(jù)文件名來判斷格式的,略過。第二個是通過流前面的幾個字節(jié)來判斷文件的格式。
public static void main(String[] args) throws IOException {
URL urlPath = new URL("xxxxxxxx");
String type = HttpURLConnection.guessContentTypeFromStream(URLUtil.getStream(urlPath));
System.out.println(type); //null
}
通過第二個方法獲得的格式輸出null,方法也不是特別合適,有些格式也判斷不出來。
最后通過url的Content-Type得出了文件的格式。
Content-Type(內(nèi)容類型),一般是指網(wǎng)頁中存在的 Content-Type,用于定義網(wǎng)絡(luò)文件的類型和網(wǎng)頁的編碼,決定瀏覽器將以什么形式、什么編碼讀取這個文件,這就是經(jīng)??吹揭恍?PHP
網(wǎng)頁點擊的結(jié)果卻是下載一個文件或一張圖片的原因。Content-Type 標(biāo)頭告訴客戶端實際返回的內(nèi)容的內(nèi)容類型。
這里引用了依賴
<!-- https://mvnrepository.com/artifact/org.apache.tika/tika-core -->
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-core</artifactId>
<version>1.22</version>
</dependency>
測試使用
public static void main(String[] args) throws IOException, MimeTypeException {
URL urlPath = new URL("xxxxxxxx");
String contentType = urlPath.openConnection().getContentType();
MimeTypes allTypes = MimeTypes.getDefaultMimeTypes();
MimeType jpeg = allTypes.forName(contentType);
System.out.println(jpeg.getExtension()); //.pdf
}
可行