获取内容类型的最快方法

Jav*_*avi 14 java url content-type

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

URL url = new URL(urlname);
URLConnection connection = url.openConnection();
connection.connect();
String contentType = connection.getContentType();
Run Code Online (Sandbox Code Playgroud)

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

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

Jav*_*avi 30

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

URL url = new URL(urlname);
HttpURLConnection connection = (HttpURLConnection)  url.openConnection();
connection.setRequestMethod("HEAD");
connection.connect();
String contentType = connection.getContentType();
Run Code Online (Sandbox Code Playgroud)


Dav*_*veH 20

如果"其他"端支持它,您可以使用HEADHTTP方法吗?


To *_*Kra 12

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

/**
 * 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;
}
Run Code Online (Sandbox Code Playgroud)

你也可以放一些计数器maxRedirectCount以避免无限重定向循环 - 但这里没有涉及.这只是一个灵感.

  • 不错.为什么你需要问:if(statusCode!= HttpURLConnection.HTTP_OK){ (2认同)