The best way to intercept a WebView request in Android

后端 未结 1 1939
广开言路
广开言路 2021-02-07 10:04

I am using a WebView in my app in which I must intercept requests. I am currently using the follwing code to do it.



        
相关标签:
1条回答
  • 2021-02-07 10:30

    There are two issues with you code

    1. Incorrect extension detection

    For example, when the code try to get resource extension for this URL:

    https://login.live.com/login.srf?wa=wsignin1.0&rpsnv=12&ct=1442476202&rver=6.4.6456.0&wp=MBI_SSL_SHARED&wreply=https:%2F%2Fmail.live.com%2Fdefault.aspx%3Frru%3Dinbox&lc=1033&id=64855&mkt=en-us&cbcxt=mai
    

    It will return aspx%3Frru%3Dinbox&lc=1033&id=64855&mkt=en-us&cbcxt=mai which is wrong. There is special method for getting extension from the URL: getFileExtensionFromUrl()

    1. According to documentation method MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext) may return null. In this case your code set wrong mime type for the page.

    Here is the method code that take into account both these issues

    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view,
        String url) {
        String ext = MimeTypeMap.getFileExtensionFromUrl(url);
        String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext);
        if (mime == null) {
            return super.shouldInterceptRequest(view, url);
        } else {
            HttpURLConnection conn = (HttpURLConnection) new URL(
                                                     url).openConnection();
            conn.setRequestProperty("User-Agent", userAgent);
            return new WebResourceResponse(mime, "UTF-8",
                                                     conn.getInputStream());
        }
    }
    
    0 讨论(0)
提交回复
热议问题