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

后端 未结 6 1158
遥遥无期
遥遥无期 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:15

    You can fetch the URL and see Content-type from the response.

    You can use the HTTP Client from apache, it helps you to fetch the content of the URL and you can use it to navigate the redirects. For instance try to fetch the following:

    http://www.youtube.com/watch?v=d4LkTstvUL4

    Will return an HTML containing the video. After a while you'll find out the video is here:

    http://www.youtube.com/v/d4LkTstvUL4

    But if you fetch that page you will get a redirect:

    HTTP/1.0 302 Redirect
    Date: Fri, 23 Jan 2009 02:25:37 GMT
    Content-Type: text/plain
    Expires: Fri, 23 Jan 2009 02:25:37 GMT
    Cache-Control: no-cache
    Server: Apache
    X-Content-Type-Options: nosniff
    Set-Cookie: VISITOR_INFO1_LIVE=sQc75zc-QSU; path=/; domain=.youtube.com; expires=
    Set-Cookie: VISITOR_INFO1_LIVE=sQc75zc-QSU; path=/; domain=.youtube.com; expires=
    Location: http://www.youtube.com/swf/l.swf?swf=http%3A//s.ytimg.com/yt/swf/cps-vf
    L4&rel=1&eurl=&iurl=http%3A//i1.ytimg.com/vi/d4LkTstvUL4/hqdefault.jpg&sk=Z_TM3JF
    e_get_video_info=1&load_modules=1
    

    So, what you have to do is to fetch the URL and examine it, until you get final content

    This section explains how to handle the redirects.

提交回复
热议问题