获取内容类型的最快方法

我需要为用户插入的url内容类型(如果是图像,音频或video)进行搜索。 我有这样的代码:

URL url = new URL(urlname); URLConnection connection = url.openConnection(); connection.connect(); String contentType = connection.getContentType(); 

我正在获取内容类型,但问题是,似乎有必要下载整个文件来检查它的内容类型。 因此,当文件非常大时,它会持续太长时间。 我需要在Google App Engine应用程序中使用它,因此请求限制为30秒。

有没有其他方法来获取url的内容类型而不下载文件(所以它可以更快地完成)?

如果“其他”端支持它,您可以使用HEAD HTTP方法吗?

感谢DaveHowes的回答和谷歌搜索如何获得HEAD我得到了这样的方式:

 URL url = new URL(urlname); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("HEAD"); connection.connect(); String contentType = connection.getContentType(); 

注意重定向,我的远程内容检查遇到了同样的问题。
这是我的修复:

 /** * Http HEAD Method to get URL content type * * @param urlString * @return content type * @throws IOException */ public static String getContentType(String urlString) throws IOException{ URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("HEAD"); if (isRedirect(connection.getResponseCode())) { String newUrl = connection.getHeaderField("Location"); // get redirect url from "location" header field logger.warn("Original request URL: '{}' redirected to: '{}'", urlString, newUrl); return getContentType(newUrl); } String contentType = connection.getContentType(); return contentType; } /** * Check status code for redirects * * @param statusCode * @return true if matched redirect group */ protected static boolean isRedirect(int statusCode) { if (statusCode != HttpURLConnection.HTTP_OK) { if (statusCode == HttpURLConnection.HTTP_MOVED_TEMP || statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == HttpURLConnection.HTTP_SEE_OTHER) { return true; } } return false; } 

您还可以为maxRedirectCount设置一些计数器以避免无限重定向循环 – 但这里不会涉及。 这只是一个灵感。