Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Detect URL mime type?

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?

like image 214
Jake Wilson Avatar asked Oct 05 '11 16:10

Jake Wilson


1 Answers

You can find out what mime type of content in such way:

webView.setDownloadListener(new DownloadListener() {
    @Override
    public void onDownloadStart(String url, String userAgent,
            String contentDisposition, String mimetype,
            long contentLength) {

        //here you getting the String mimetype
        //and you can do with it whatever you want
    }
});

In this method you can check if mimetype is pdf and show it through Google Docs in WebView using modified url like this:

String pdfPrefixUrl = "https://docs.google.com/gview?embedded=true&url="

if ("application/pdf".equals(mimetype)) {
     String newUrl = pdfPrefixUrl + url;
     webView.loadUrl(newUrl);
}    

Hope it will help!

like image 188
Yazon2006 Avatar answered Oct 06 '22 18:10

Yazon2006