如何在UIWebView请求中添加自定义HTTP标头,我的UIWebView基于Cordova项目? [英] How to add customize HTTP headers in UIWebView request, my UIWebView is based on Cordova project?

查看:90
本文介绍了如何在UIWebView请求中添加自定义HTTP标头,我的UIWebView基于Cordova项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的iOS UIWebView页面基于Cordova开源框架,我想在其webview URL请求中添加一些自定义http标头,我的解决方案是在以下UIWebView委托方法中添加它们。

My iOS UIWebView page is based on Cordova open source framework, and I want to add some customize http headers in its webview URL request, my solution is to add them in the following UIWebView delegate method.

Debug显示标题已成功添加,但实际上请求并未将它们删除。使用Wireshark捕获网络数据包,发现只有标准标头可用,没有我的自定义标头。

Debug shows that headers are added successfully, but in fact the request doesn't bring them out. Using Wireshark to capture network packets and found only standard headers are available, no my customize ones.

我的测试基于模拟器(iOS 7.1),任何有此主题经验的人都可以提前分享和讨论。

My testing is based on simulator (iOS 7.1), anyone who has experience on this topic please share and discuss together, thanks in advance.

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    // Add customize http headers in UIWebView request
    if([request isKindOfClass:[NSMutableURLRequest class]]) {        

        NSMutableURLRequest * mRequest = (NSMutableURLRequest *)request;
        [mRequest setValue:@"1.1" forHTTPHeaderField:@"appVersion"];
        [mRequest setValue:@"iPhone 4S" forHTTPHeaderField:@"deviceModel"];
    }

    return [super webView:webView shouldStartLoadWithRequest:request navigationType:navigationType];
}


推荐答案

你有两个选择要么创建 NSMutableUrlRequest at a at使用webView loadReqest启动和加载,或者使用 NSURLProtocol

You have two options either create a NSMutableUrlRequest at the start and load that with webView loadReqest or take over the complete URL loading of your app with NSURLProtocol.

最简单的方法是首选,因为它只有一行额外代码:

The most easiest way is the first choice as its only one extra lines of code:

[webView loadRequest:mRequest];

第二种选择使用 NSURLProtocol 接管应用程序的URL加载。这涉及使用创建具体类来注册自己的解决方案。覆盖的主要方法是 canonicalRequestForRequest

The second choice uses NSURLProtocol to take over URL loading of your app. this involves registering your own solution using creating a concrete class. the main method to override is canonicalRequestForRequest.

我建议你看看这两个教程 NSNipster raywenderlich 指南。

I suggest you take a look at these two tutorials NSNipster and raywenderlich for guides.

这篇关于如何在UIWebView请求中添加自定义HTTP标头,我的UIWebView基于Cordova项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆