使用google doc拦截webview中的响应代码以显示pdf

时间:2014-08-06 21:23:59

标签: android android-webview

我有一个webview,可以在其中加载带有传单(pdf,来自网络)的Google文档。有些传单在我的网站上有,但其他传单没有,但我在应用程序中编码,所以当它们可用时,用户将会看到它们。
webview中的google doc适用于可用的传单,但是那些不可用但我在google doc中收到错误类型的消息。我想拦截带有传单的URL中的404响应代码错误(pdf)。我该怎么做?

当前代码:

/*opens in app using google docs*/
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setPluginState(PluginState.ON);      
mWebView.loadUrl("https://docs.google.com/viewer?url="+round_num_url);
//round_num_url is the url for my flyer

Google浏览器中的google doc for flyers不可用 - “抱歉,我们无法在原始来源找到该文档。验证文档是否仍然存在。您也可以尝试通过点击器下载原始文档”

编辑:从@ x-code

获取建议后仍然无效(崩溃)
try {
            URL url = new URL(round_num_url);
            HttpURLConnection huc = (HttpURLConnection) url.openConnection();
            huc.setRequestMethod("HEAD");
            huc.connect();
            if (huc.getResponseCode() != 404) {
              // the pdf is available, continue with your code that loads the web view
              // ...
            } else {
              // the pdf is not available, you may need to notify the user
              // ...
            }
            huc.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch(IOException e) {
            e.printStackTrace();
        }

1 个答案:

答案 0 :(得分:0)

虽然Google文档在尝试访问您的损坏网址时会收到404,但它不会将404返回到网络视图,因为Google文档网址有效。

您应首先尝试使用AndroidHttpClient和HttpHead请求加载它来测试您自己的网址(PDF的网址)。如果这返回404则不要试图加载gdocs。

以下是一些示例代码。我使用了HttpUrlConnection,因为这是Android文档为新代码推荐的方法:

HttpUrlConnection huc = new HttpUrlConnection(round_num_url);
huc.setRequestMethod("HEAD");
huc.connect();
if (huc.getResponseCode() != 404) {
  // the pdf is available, continue with your code that loads the web view
  // ...
} else {
  // the pdf is not available, you may need to notify the user
  // ...
}
huc.disconnect();

我没有编译这段代码,你可能需要在编译之前将它包装在try / catch块中。

更新:我必须修改代码才能使其正常工作,如上所述:

try {
    URL url = new URL(strUrl);
    HttpURLConnection huc = (HttpURLConnection) url.openConnection();
    try {
        if (huc.getResponseCode() != 404) {
            // url is available
        } else {
            // url is not available
        }
    } finally {
        huc.disconnect();
    }
} catch (MalformedURLException e) {
    ;
} catch (IOException e) {
    ;
}
相关问题