使用UIWebView loadRequest发送自定义标头 [英] Send custom headers with UIWebView loadRequest

查看:91
本文介绍了使用UIWebView loadRequest发送自定义标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够使用我的UIWebView loadRequest 方法发送一些额外的标题。

I want to be able to send some extra headers with my UIWebView loadRequest method.

我试过了:

NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.reliply.org/tools/requestheaders.php"]];
[req addValue:@"hello" forHTTPHeaderField:@"aHeader"];

[self.theWebView loadRequest:req];

我也试过继承 UIWebView 并且截取 - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)请求navigationType:(UIWebViewNavigationType)navigationType 方法。

I have also tried subclassing the UIWebView and intercepting the - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType method.

在那个方法中,我有一段看起来像这样的代码:

In that method I had a block of code which looked like this:

NSMutableURLRequest *newRequest = [request mutableCopy];
for(NSString *key in [customHeaders allKeys]) {
    [newRequest setValue:[customHeaders valueForKey:key] forHTTPHeaderField:key];
}
[self loadRequest:newRequest];

但由于某些未知原因导致网页视图无法加载任何内容(空白框架)和错误消息 NSURLErrorCancelled(-999)出现(所有已知的修复程序都没有为我修复)。

But for some unknown reason it was causing the web view to not load anything (blank frame) and the error message NSURLErrorCancelled (-999) comes up (all known fixes don't fix it for me).

所以我不知道该怎么做。如何发送自定义标题以及 UIWebView 请求?

So I am at a loss as to what to do. How can I send a custom header along with a UIWebView request?

非常感谢!

推荐答案

我发现这是向我的UIWebView请求添加标题的方法 - 覆盖此委托方法:

I found that this was the way to add headers to my UIWebView request - override this delegate method:

- (BOOL) webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType) navigationType

使用以下代码:

BOOL headerIsPresent = [[request allHTTPHeaderFields] objectForKey:@"my custom header"]!=nil;

if(headerIsPresent) return YES;

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSURL *url = [request URL];
        NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];

        // set the new headers
        for(NSString *key in [self.customHeaders allKeys]){
            [request addValue:[self.customHeaders objectForKey:key] forHTTPHeaderField:key];
        }

        // reload the request
        [self loadRequest:request];
    });
});
return NO;

这篇关于使用UIWebView loadRequest发送自定义标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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