In my Android app, I have various URLs that I access from a database and then open a WebView to display that URL. Typically the url looks something like this:
http://www.mysite.com/referral.php?id=12345
These referral links always redirect/forward to another url. Sometimes the resulting url is directly to an image. Sometimes it's to a PDF. Sometimes it's to just another HTML page.
Anyways, I need to be able to distinguish between these different types of pages. For example, if the resulting URL links to a PDF file, I want to use the Google Docs Viewer trick to display it. If it's just a plain HTML page I want to simply display it and if it's an image, I am planning on downloading the image and displaying it in my app in a certain way.
I figure the best way to approach this is to determine the mime type of the resulting url. How do you do this? And is there a better way to accomplish what I want?
I think content type http header should do the trick:
Content type
You can find out what mime type of content in such way:
In this method you can check if mimetype is pdf and show it through Google Docs in WebView using modified url like this:
Hope it will help!
Here is my solution to get mime type.
It also works on main thread (UI) and provides a B plan to guess mime type (not 100% sure though)
Notes:
I added a 150 ms timeout: feel free to tune that, or remove it if you call this from outside the main thread (and it's ok for you to wait for URLCconnection to do it's job). Also, the ThreadPolicy stuff is useless if you use this outside the main thread. about that...
For those who wonder why I allow network on main thread, here is the reason:
I had to find a way to get mime type from main thread because WebViewClient. shouldOverrideKeyEvent (WebView view, KeyEvent event) is called in main thread and my implementation of it needs to know the mime type in order to return the appropriate value (true or false)