草庐IT

Android:WebView shouldInterceptRequest 不在 WebView 中添加 RequestProperties

coder 2023-12-05 原文

我正在使用 shouldInterceptRequest 拦截来自 webview 的请求

下面是我返回 WebResourceResponse 的代码

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private static WebResourceResponse handleRequestViaUrlOnly(WebResourceRequest webResourceRequest){
        String url = webResourceRequest.getUrl().toString();
        Log.i("intercepting req....!!!", url);
        String ext = MimeTypeMap.getFileExtensionFromUrl(url);
        String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext);

        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setRequestProperty("Sample-Header", "hello");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            return new WebResourceResponse(mime, "UTF-8", conn.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

我在我的 CustomWebViewClient 中调用这个方法

class CustomWebViewClient extends WebViewClient {

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
        return handleRequestViaUrlOnly(request);
    }
}

但是,当我在 chrome://inspect/#devices 中检查来自 WebView 远程调试器的请求 header 时。

我添加的额外 RequestProperty 不存在。

conn.setRequestProperty("Sample-Header", "hello");

WebView 的请求 header 中不存在 Sample-Header。

我错过了什么吗?我将不胜感激。

最佳答案

所以问题是,当您传递 conn.getInputStream() 时,它只提供数据。可以通过 conn.getHeaderFields() 提取响应 header 。此外,除非服务器支持它并且CORS,否则您将无法取回额外的 header 。没有参与。这是连接的 wireshark 输出

GET /~fdc/sample.html HTTP/1.1
Sample-Header: hello
Content-Type: application/x-www-form-urlencoded
User-Agent: Dalvik/2.1.0 (Linux; U; Android 7.1; Android SDK built for x86_64 Build/NPF26K)
Host: www.columbia.edu
Connection: Keep-Alive
Accept-Encoding: gzip
Content-Length: 0

HTTP/1.1 200 OK
Date: Wed, 01 Mar 2017 09:06:58 GMT
Server: Apache
Last-Modified: Thu, 22 Apr 2004 15:52:25 GMT
Accept-Ranges: bytes
Vary: Accept-Encoding,User-Agent
Content-Encoding: gzip
Content-Length: 8664
Keep-Alive: timeout=15, max=99
Connection: Keep-Alive
Content-Type: text/html

如您所见,响应中没有 Sample-Header: hello header 。

下面是从响应构建 WebResourceResponse header 并将您的自定义 header 附加到它的简单代码:

webView.setWebViewClient(new WebViewClient() {
    private Map<String, String> convertResponseHeaders(Map<String, List<String>> headers) {
        Map<String, String> responseHeaders = new HashMap<>();
        responseHeaders.put("Sample-Header", "hello");

        for (Map.Entry<String, List<String>> item : headers.entrySet()) {
            List<String> values = new ArrayList<String>();

            for (String headerVal : item.getValue()) {
                values.add(headerVal);
            }
            String value = StringUtil.join(values, ",");
            Log.e(TAG, "processRequest: " + item.getKey() + " : " + value);

            responseHeaders.put(item.getKey(), value);
        }

        return responseHeaders;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
        final String method = request.getMethod();
        final String url = request.getUrl().toString();
        Log.d(TAG, "processRequest: " + url + " method " + method);
        String ext = MimeTypeMap.getFileExtensionFromUrl(url);
        String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext);

        try {
            HttpURLConnection conn = (HttpURLConnection)new URL(url).openConnection();
            conn.setRequestMethod(method);
            conn.setRequestProperty("Sample-Header", "hello");
            conn.setDoInput(true);
            conn.setUseCaches(false);

            Map<String, String> responseHeaders = convertResponseHeaders(conn.getHeaderFields());

            responseHeaders.put("Sample-Header", "hello");

            return new WebResourceResponse(
                    mime,
                    conn.getContentEncoding(),
                    conn.getResponseCode(),
                    conn.getResponseMessage(),
                    responseHeaders,
                    conn.getInputStream()
                    );

        } catch (Exception e) {
            Log.e(TAG, "shouldInterceptRequest: " + e);
        }
        return null;
    }
});

关于Android:WebView shouldInterceptRequest 不在 WebView 中添加 RequestProperties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41869163/

有关Android:WebView shouldInterceptRequest 不在 WebView 中添加 RequestProperties的更多相关文章

  1. ruby - 我需要将 Bundler 本身添加到 Gemfile 中吗? - 2

    当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/

  2. ruby - 将 Bootstrap Less 添加到 Sinatra - 2

    我有一个ModularSinatra应用程序,我正在尝试将Bootstrap添加到应用程序中。get'/bootstrap/application.css'doless:"bootstrap/bootstrap"end我在views/bootstrap中有所有less文件,包括bootstrap.less。我收到这个错误:Less::ParseErrorat/bootstrap/application.css'reset.less'wasn'tfound.Bootstrap.less的第一行是://CSSReset@import"reset.less";我尝试了所有不同的路径格式,但它

  3. ruby-on-rails - form_for 中不在模型中的自定义字段 - 2

    我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢

  4. ruby - 续集在添加关联时访问many_to_many连接表 - 2

    我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以

  5. ruby - 当使用::指定模块时,为什么 Ruby 不在更高范围内查找类? - 2

    我刚刚被困在这个问题上一段时间了。以这个基地为例:moduleTopclassTestendmoduleFooendend稍后,我可以通过这样做在Foo中定义扩展Test的类:moduleTopmoduleFooclassSomeTest但是,如果我尝试通过使用::指定模块来最小化缩进:moduleTop::FooclassFailure这失败了:NameError:uninitializedconstantTop::Foo::Test这是一个错误,还是仅仅是Ruby解析变量名的方式的逻辑结果? 最佳答案 Isthisabug,or

  6. ruby - 可以通过多少种方法将方法添加到 ruby​​ 对象? - 2

    当谈到运行时自省(introspection)和动态代码生成时,我认为ruby​​没有任何竞争对手,可能除了一些lisp方言。前几天,我正在做一些代码练习来探索ruby​​的动态功能,我开始想知道如何向现有对象添加方法。以下是我能想到的3种方法:obj=Object.new#addamethoddirectlydefobj.new_method...end#addamethodindirectlywiththesingletonclassclass这只是冰山一角,因为我还没有探索instance_eval、module_eval和define_method的各种组合。是否有在线/离线资

  7. ruby - 如何在 Ruby 中向现有方法定义添加语句 - 2

    我注意到类定义,如果我打开classMyClass,并在不覆盖的情况下添加一些东西我仍然得到了之前定义的原始方法。添加的新语句扩充了现有语句。但是对于方法定义,我仍然想要与类定义相同的行为,但是当我打开defmy_method时似乎,def中的现有语句和end被覆盖了,我需要重写一遍。那么有什么方法可以使方法定义的行为与定义相同,类似于super,但不一定是子类? 最佳答案 我想您正在寻找alias_method:classAalias_method:old_func,:funcdeffuncold_func#similartoca

  8. ruby-on-rails - 添加回形针新样式不影响旧上传的图像 - 2

    我有带有Logo图像的公司模型has_attached_file:logo我用他们的Logo创建了许多公司。现在,我需要添加新样式has_attached_file:logo,:styles=>{:small=>"30x15>",:medium=>"155x85>"}我是否应该重新上传所有旧数据以重新生成新样式?我不这么认为……或者有什么rake任务可以重新生成样式吗? 最佳答案 参见Thumbnail-Generation.如果rake任务不适合你,你应该能够在控制台中使用一个片段来调用重新处理!关于相关公司

  9. ruby - 我如何添加二进制数据来遏制 POST - 2

    我正在尝试使用Curbgem执行以下POST以解析云curl-XPOST\-H"X-Parse-Application-Id:PARSE_APP_ID"\-H"X-Parse-REST-API-Key:PARSE_API_KEY"\-H"Content-Type:image/jpeg"\--data-binary'@myPicture.jpg'\https://api.parse.com/1/files/pic.jpg用这个:curl=Curl::Easy.new("https://api.parse.com/1/files/lion.jpg")curl.multipart_form_

  10. 安卓apk修改(Android反编译apk) - 2

    最近因为项目需要,需要将Android手机系统自带的某个系统软件反编译并更改里面某个资源,并重新打包,签名生成新的自定义的apk,下面我来介绍一下我的实现过程。APK修改,分为以下几步:反编译解包,修改,重打包,修改签名等步骤。安卓apk修改准备工作1.系统配置好JavaJDK环境变量2.需要root权限的手机(针对系统自带apk,其他软件免root)3.Auto-Sign签名工具4.apktool工具安卓apk修改开始反编译本文拿Android系统里面的Settings.apk做demo,具体如何将apk获取出来在此就不过多介绍了,直接进入主题:按键win+R输入cmd,打开命令窗口,并将路

随机推荐