我試圖攔截來自WebView的請求,以便我可以注入額外的標頭。我正在將WebViewClient應用於WebView並覆蓋shouldInterceptRequest()
。如何處理WebExceptionClient.shouldInterceptRequest()中的IOException
在shouldInterceptRequest()
我打開連接,添加標題,然後在WebResourceResponse中返回打開的流。
我不清楚如果初始打開連接失敗時應如何處理IOException。
final Map<String, String> extraHeaders = getExtraHeaders(intent);
webview.setWebViewClient(new WebViewClient() {
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
final Uri uri = request.getUrl();
try {
URL url = new URL(uri.toString());
URLConnection con = url.openConnection();
for (Map.Entry<String, String> h : extraHeaders.entrySet()) {
con.addRequestProperty(h.getKey(), h.getValue());
}
final String contentType = con.getContentType().split(";")[0];
final String encoding = con.getContentEncoding();
return new WebResourceResponse(contentType, encoding, con.getInputStream());
} catch (IOException e) {
// what should we do now?
e.printStackTrace();
}
return super.shouldInterceptRequest(view, request);
}
});
我不能離開它未捕獲的,因爲它是一個檢查異常,是不是shouldInterceptRequest()
簽名的一部分。
我無法將其包裝在一個未經檢查的異常中,因爲那樣會被WebView取消並殺死應用程序。
如果我發現並忽略異常,並且默認爲super
方法(它剛剛返回null
),那麼WebView將繼續其默認行爲並嘗試發送請求(沒有我的額外頭文件)。這是不可取的,因爲WebView自己的連接嘗試可能實際上取得成功,並且缺失的標題會導致更多問題。
似乎沒有辦法表明攔截失敗,請求應該中止。
這裏做的最好的事情是什麼?
我試圖返回一個模擬失敗響應,但這不被視爲錯誤。 WebView將顯示包含響應內容的頁面(來自異常的錯誤消息),並且不調用WebViewClient的回調函數onReceivedError()
或onReceivedHttpError()
回調。
} catch (IOException e) {
InputStream is = new ByteArrayInputStream(e.getMessage().getBytes());
return new WebResourceResponse("text/plain", "UTF-8", 500, "Intercept failed",
Collections.<String, String>emptyMap(),
is);
}
這不回答問題。我知道什麼是IOException。 –