4

I have an app which need different action based on the content from an URL. If the content is a file, I need to download it. But, if the content is a webpage, I need to open it. As far I know, there are two URL types:

And the example for webpage: https://stackoverflow.com/questions/xxxxxx/how-to-check-a-url-contain

I only have the following code to parse a String to URL:

String requestUrl = "https://dl-ssl.google.com/android/repository/android-14_r04.zip";
URL url = new URL(requestUrl);

So, my questions:

  • How can I check the content? Is it a file or webpage?

  • If it's a file, how can I check the content from undirect link?

Thanks in advance.

Community
  • 1
  • 1
Anggrayudi H
  • 14,977
  • 11
  • 54
  • 87
  • 1
    Open it and check the headers - if it is "application/html" it seems to be a web page. – Smutje Jan 16 '15 at 07:01
  • 1
    text/html, but that's the idea. – chrylis -cautiouslyoptimistic- Jan 16 '15 at 07:15
  • 1
    In general, URLs do not map to the server's filesystem, even though many web servers like Apache do this by default, so you should consider a different approach (content-type header is good, if it's OK to connect to the URL). Consider web apps that might use URLs like http://www.example.com/category/subcategory/article and http://www.example.com/download/category/filename — the resource identifiers are unrelated to the filesystem or file names. Furthermore, sometimes you'll have http://www.example.com/downloadarea/file.zip which is in fact a webpage with info and a link to download the file. – Laogeodritt Jan 16 '15 at 08:42

2 Answers2

4

you can check content type:

    URLConnection c = url.openConnection();
    String contentType = c.getContentType();

for html - text/html; charset=utf-8; for zip - application/zip

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
0

Permit me to add my answer though this question is a year old.

Android provides a URL utility that can check many options based on URL. Try:

        URLUtil.isFileUrl(URL)

Other options includes isDataUrl, isContentUrl etc.

Thanks

CanCoder
  • 1,073
  • 14
  • 20
  • 1
    Nope, this answer is incorrect. isFileUrl() will return true, if URL starts with "file:", "file:///android_asset/" or "file:///cookieless_proxy/" – Lev Leontev Mar 06 '20 at 14:45