在我的Android应用程序中,我有从数据库访问的各种URL,然后打开WebView以显示该URL。通常,网址看起来像这样:
http://www.mysite.com/referral.php?id=12345
这些引荐链接始终重定向/转发到另一个网址。有时,生成的URL直接显示在图像上。有时它是PDF。有时它只是另一个HTML页面。
无论如何,我需要能够区分这些不同类型的页面。例如,如果生成的URL链接到PDF文件,我想使用Google Docs Viewer技巧来显示它。如果它只是一个简单的HTML页面,我想简单地显示它,如果它是一个图像,我打算下载图像并以某种方式在我的应用程序中显示它。
我认为解决此问题的最佳方法是确定生成的网址的mime类型。你怎么做到这一点?是否有更好的方法来实现我想要的目标?
答案 0 :(得分:5)
您可以通过以下方式找出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
}
});
在此方法中,您可以检查mimetype是否为pdf,并使用修改后的网址在WebView中通过Google文档显示:
String pdfPrefixUrl = "https://docs.google.com/gview?embedded=true&url="
if ("application/pdf".equals(mimetype)) {
String newUrl = pdfPrefixUrl + url;
webView.loadUrl(newUrl);
}
希望它会有所帮助!
答案 1 :(得分:0)
我认为内容类型http标头可以解决这个问题:
答案 2 :(得分:-2)
这是我获取mime类型的解决方案。
它也可以在主线程(UI)上运行并提供 B计划来猜测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毫秒超时:随意调整,或者如果从主线程外部调用它,则将其删除(您可以等待URLC连接执行此操作这是工作)。另外,如果你在主线程之外使用它,ThreadPolicy的东西是没用的。关于那......
对于那些想知道为什么我在主线程上允许网络的人,原因如下:
我必须找到一种从主线程获取mime类型的方法,因为在主线程中调用 WebViewClient. shouldOverrideKeyEvent (WebView view, KeyEvent event) 并且我的实现需要知道mime类型才能返回适当的值(真或假)