1. 程式人生 > >Android 攔截WebView請求,並加入或修改引數(GET)

Android 攔截WebView請求,並加入或修改引數(GET)

今天遇到一個需求,H5內部呼叫登入請求,然後手機端給他拼接使用者的ID及其他訊息

這個WebView提供了方法shouldInterceptRequest

下面程式碼,只是簡單demo,請求方式是get

mWebView.setWebViewClient(new WebViewClient() {
    @Nullable
    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
        if (url.contains("UserName")) {
            URL urlStr = null;
            try {
                urlStr = new URL(url+"?userId=12");
                URLConnection rulConnection = urlStr.openConnection();
                HttpURLConnection conn = (HttpURLConnection) rulConnection;
                conn.setRequestProperty("Accept-Charset", "utf-8");
                conn.setRequestProperty("contentType", "utf-8");
                conn.setRequestMethod("GET");
                // Read input
                String charset = conn.getContentEncoding() != null ? conn.getContentEncoding() : Charset.defaultCharset().displayName();
                String mime = conn.getContentType();
                InputStream isContents = conn.getInputStream();
                return new WebResourceResponse(mime, charset,
                        isContents);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        } else {
            return super.shouldInterceptRequest(view, url);
        }
    }
});