Android WebView内所有请求实现自定义Header

查阅网上诸多方法无效,本文方法亲测有效

原理:复写shouldInterceptRequest拦截请求,使用OkHttp等客户端请求工具实现代理请求

缺点:无法拦截并获取WebView内部POST请求参数,导致POST请求失败(解决见下一篇文章)

public class MainActivity extends AppCompatActivity {

    private String mUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        StatusBarUtil.setLightMode(this);
        StatusBarUtil.setTransparent(this);
        StatusBarUtil.setColor(this, Color.WHITE, 0);
        mLinearLayout = this.findViewById(R.id.container);
        mUrl = "https://checkout.appblog.cn/xxxxxx";
        initView();
    }

    private void initView() {
        Map<String, String> webviewHeader =new HashMap<>();
        //此方法无效
        webviewHeader.put("Referer", "www.appblog.cn");
        webviewHeader.put("referrer", "www.appblog.cn");

        WebView webView = findViewById(R.id.web_view);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setDomStorageEnabled(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setSavePassword(true);
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSettings.setUseWideViewPort(true);

        webView.setWebViewClient(new WebViewClient(webView) {
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                String url = request.getUrl().toString();
                Log.i("yezhou", request.getUrl().toString());
                if (url.contains("gateway")) {
                    return getNewResponse(request);
                } else {
                    return super.shouldInterceptRequest(view, request);
                }
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }
        });

        webView.loadUrl(mUrl, webviewHeader);
    }

    private WebResourceResponse getNewResponse(WriteHandlingWebResourceRequest resourceRequest) {
        try {
            OkHttpClient httpClient = new OkHttpClient();
            String url = resourceRequest.getUrl().toString();

            Request.Builder builder = new Request.Builder();
            //Request request = new Request.Builder()
            builder.url(url.trim());
            if (url.contains("gateway")) {
                builder.addHeader("referrer", "www.appblog.cn"); // Example header
            }
            if ("POST".equalsIgnoreCase(resourceRequest.getMethod())) {
                builder.post(RequestBody.create(resourceRequest.getAjaxData().getBytes()));
            }
            Request request = builder.build();

            Response response = httpClient.newCall(request).execute();

            return new WebResourceResponse(
                    null,
                    response.header("content-encoding", "utf-8"),
                    response.body().byteStream()
            );

        } catch (Exception e) {
            return null;
        }
    }
}

版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/03/30/android-webview-implement-custom-headers-for-all-requests/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
海报
Android WebView内所有请求实现自定义Header
查阅网上诸多方法无效,本文方法亲测有效 原理:复写shouldInterceptRequest拦截请求,使用OkHttp等客户端请求工具实现代理请求 缺点:无法拦截并获取WebView……
<<上一篇
下一篇>>
文章目录
关闭
目 录