How to determine if a given URL link is a video or image?

后端 未结 6 1157
遥遥无期
遥遥无期 2021-01-18 15:06

I\'m trying to take a given URL entered by user and determine if the URL is pointing to a image or a video.

Example use case:

When a user paste in the URL o

6条回答
  •  清歌不尽
    2021-01-18 15:10

    This is a solution without apache.

    HttpURLConnection urlConnection;
    String urlString = "http://www.youtube.com/v/oHg5SJYRHA0";
    try {
        urlConnection = (HttpURLConnection) new URL(urlString).openConnection();
        urlConnection.setInstanceFollowRedirects(true);
        HttpURLConnection.setFollowRedirects(true);
    
        int status = urlConnection.getResponseCode();
        if (status >= 300 && status <= 307) {
            urlString = urlConnection.getHeaderField("Location");
            urlConnection = (HttpURLConnection) new URL(urlString).openConnection();
            System.out.println("Redirect to URL : " + urlString);
        }
        String contentType = urlConnection.getHeaderField("Content-Type");
        if (contentType.startsWith("image/")) {
            //do something with an image
        } else if (contentType.equals("application/x-shockwave-flash")) {
            //do something with a video
            //} else ...
        }
        System.out.println(contentType);
    } catch (IOException e) {
        e.printStackTrace();
    }
    

    Follow Redirect Example from mkyong.com

提交回复
热议问题