Android - Detect Url Mime Type?
Solution 1:
You can find out what mime type of content in such way:
webView.setDownloadListener(newDownloadListener() {
@OverridepublicvoidonDownloadStart(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:
StringpdfPrefixUrl="https://docs.google.com/gview?embedded=true&url="if ("application/pdf".equals(mimetype)) {
StringnewUrl= pdfPrefixUrl + url;
webView.loadUrl(newUrl);
}
Hope it will help!
Solution 2:
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)
import java.net.URL;
import java.net.URLConnection;
publicstatic String getMimeType(String url)
{
StringmimeType=null;
// this is to handle call from main thread
StrictMode.ThreadPolicyprviousThreadPolicy= StrictMode.getThreadPolicy();
// temporary allow network access main thread// in order to get mime type from content-type
StrictMode.ThreadPolicypermitAllPolicy=newStrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(permitAllPolicy);
try
{
URLConnectionconnection=newURL(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 urltry
{
mimeType = URLConnection.guessContentTypeFromName(url);
}
catch (Exception ignored)
{
}
Log.i("", "mimeType guessed from url "+ mimeType);
}
return mimeType;
}
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)
Solution 3:
I think content type http header should do the trick:
Post a Comment for "Android - Detect Url Mime Type?"