Android - 检测 URL mime 类型?
在我的 Android 应用程序中,我有从数据库访问的各种 URL,然后打开 WebView 来显示该 URL。通常,该 url 看起来像这样:
http://www.mysite.com/referral.php?id=12345
这些引用链接总是重定向/转发到另一个 url。有时,生成的 url 直接指向图像。有时是 PDF。有时只是另一个 HTML 页面。
无论如何,我需要能够区分这些不同类型的页面。例如,如果生成的 URL 链接到 PDF 文件,我想使用 Google Docs Viewer 技巧来显示它。如果它只是一个普通的 HTML 页面,我想简单地显示它,如果它是一个图像,我计划下载该图像并以某种方式在我的应用程序中显示它。
我认为解决此问题的最佳方法是确定生成的 url 的 mime 类型。你如何做到这一点?还有更好的方法来实现我想要的吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以通过以下方式找出内容的 mime 类型:
在这种方法中,您可以检查 mimetype 是否为 pdf,并使用修改后的 url 通过 Google Docs 在 WebView 中显示它,如下所示:
希望它会有所帮助!
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!
这是我获取 mime 类型的解决方案。
它还可以在主线程 (UI) 上运行,并提供 B 计划来猜测 MIME 类型(但不是 100% 确定)
注释:
我添加了 150 毫秒超时:请随意调整它,或者如果您从主线程外部调用它,请将其删除(并且您可以等待 URLCconnection 完成它的工作)。另外,如果您在主线程之外使用 ThreadPolicy,那么 ThreadPolicy 的东西就没用了。关于这一点...
对于那些想知道为什么我在主线程上允许网络的人,原因如下:
我必须找到一种从主线程获取 mime 类型的方法,因为 WebViewClient。 shouldOverrideKeyEvent (WebView view, KeyEvent event) 在主线程中调用,我的实现需要知道 mime 类型才能返回适当的值(true 或 false)
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)
我认为内容类型http标头应该可以解决问题:
内容类型
I think content type http header should do the trick:
Content type