Quickest way to get content type

前端 未结 3 1127
感情败类
感情败类 2020-12-06 04:58

I need to chech for the content type (if it\'s image, audio or video) of an url which has been inserted by the user. I have a code like this:

URL url = new U         


        
相关标签:
3条回答
  • 2020-12-06 05:50

    If the "other" end supports it, could you use the HEAD HTTP method?

    0 讨论(0)
  • 2020-12-06 05:50

    Thanks to DaveHowes answer and googling around about how to get HEAD I got it in this way:

    URL url = new URL(urlname);
    HttpURLConnection connection = (HttpURLConnection)  url.openConnection();
    connection.setRequestMethod("HEAD");
    connection.connect();
    String contentType = connection.getContentType();
    
    0 讨论(0)
  • 2020-12-06 05:53

    Be aware of redirects, I faced same problem with my remote content check.
    Here is my fix:

    /**
     * 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;
    }
    

    You could also put some counter for maxRedirectCount to avoid infinite redirects loop - but this is not covered here. This is just a inspiration.

    0 讨论(0)
提交回复
热议问题