2011-10-05 257 views
3

在我的Android應用程序中,我有從數據庫訪問的各種URL,然後打開WebView以顯示該URL。通常,url看起來像這樣:Android - 檢測URL MIME類型?

http://www.mysite.com/referral.php?id=12345 

這些引薦鏈接總是重定向/轉發到另一個url。有時生成的網址直接映射到圖片。有時候是以PDF格式。有時候只是另一個HTML頁面。

無論如何,我需要能夠區分這些不同類型的網頁。例如,如果生成的網址鏈接到PDF文件,我想使用Google文檔查看器技巧來顯示它。如果它只是一個簡單的HTML頁面,我只想簡單地顯示它,如果它是一個圖像,我打算下載圖像並以某種方式顯示在我的應用程序中。

我想這是最好的方法來確定MIME類型的結果網址。你怎麼做到這一點?有沒有更好的方式來實現我想要的?

回答

0

我認爲,內容類型HTTP頭應該做的伎倆:

Content type

+0

任何線索如何訪問Android中的標題? –

+0

你正在使用AndroidHTTPClient或類似的東西來獲取這些鏈接的內容?如果是,那麼你應該在HTTP客戶端類返回的HttpResponse對象中有getHeaders方法。 – Mateusz

+0

我想通了。我使用'HttpClient','HttpGet'和'HttpResponse'來檢索標題並查找'Content-Type'標題。謝謝! –

-2

這裏是我的解決方案來獲得MIME類型。

它也在主線程(UI)並提供薪酬計劃猜測MIME類型(不是100%肯定雖然)

import java.net.URL; 
import java.net.URLConnection; 

public static String getMimeType(String url) 
{ 
    String mimeType = null; 

    // this is to handle call from main thread 
    StrictMode.ThreadPolicy prviousThreadPolicy = StrictMode.getThreadPolicy(); 

    // temporary allow network access main thread 
    // in order to get mime type from content-type 

    StrictMode.ThreadPolicy permitAllPolicy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
    StrictMode.setThreadPolicy(permitAllPolicy); 

    try 
    { 
     URLConnection connection = new URL(url).openConnection(); 
     connection.setConnectTimeout(150); 
     connection.setReadTimeout(150); 
     mimeType = connection.getContentType(); 
     Log.i("", "mimeType from content-type "+ mimeType); 
    } 
    catch (Exception ignored) 
    { 
    } 
    finally 
    { 
     // restore main thread's default network access policy 
     StrictMode.setThreadPolicy(prviousThreadPolicy); 
    } 

    if(mimeType == null) 
    { 
     // Our B plan: guessing from from url 
     try 
     { 
      mimeType = URLConnection.guessContentTypeFromName(url); 
     } 
     catch (Exception ignored) 
     { 
     } 
     Log.i("", "mimeType guessed from url "+ mimeType); 
    } 
    return mimeType; 
} 

注:

  • 我添加了一個150毫秒超時:隨意調整,或刪除它,如果你從主線外調用它(並且您可以等待URLCconnection完成它的工作)。另外,如果你在主線程之外使用這個,ThreadPolicy的東西是沒用的。有關...

  • 對於那些誰不知道爲什麼我讓網絡上的主線程,這裏的原因是:

    我必須找到一種方法,從主線程獲取的MIME類型,因爲WebViewClient. shouldOverrideKeyEvent (WebView view, KeyEvent event)是所謂在主線程我實現的,它需要知道MIME類型,以返回適當的值(true或false)

4

你可以找出在這種方式的MIME內容類型:

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 
    } 
}); 

在這種方法中,你可以檢查,如果MIME類型是PDF格式,並使用修改後的URL像這樣的WebView顯示它通過谷歌文檔:

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

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

希望這將有助於!