用UIWebView loadRequest发送自定义标题

我想能够发送一些额外的头与我的UIWebView loadRequest方法。

我努力了:

 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 *)request navigationType:(UIWebViewNavigationType)navigationType方法。

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

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

但由于一些未知的原因,它导致网页视图不加载任何东西(空白帧)和错误消息NSURLErrorCancelled (-999)出现(所有已知的修补程序不能解决这个问题)。

所以我不知道该怎么做。 我怎样才能发送一个自定义标题与一个UIWebView请求?

非常感谢!

我发现这是添加头到我的UIWebView请求的方式 – 重写这个委托方法:

 - (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; 

Thomas的答案不适用于(多数)带有多个iFrame的网页。 该解决scheme将通过完整的UIWebView加载一个iFrame请求。 例如,如果它为Google advt调用loadRequest。 (这是在一些小的iFrame)advt。 被加载到整个UIWebView&没有别的。

我find另一种方法,可以使用NSURLProtocol

 -(BOOL)webView:(IMYVKWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { NSMutableDictionary* mapObject = [NSMutableDictionary dictionary]; mapObject[@"headers"] = request.allHTTPHeaderFields; mapObject[@"navigationType"] = @(navigationType); [webViewRequestMap setObject:mapObject forKey:request.URL.absoluteString]; return YES; } 

webViewRequestMap是静态的NSMutableDictionary *

在您的自定义NSURLProtocol代码中:

  @interface IMYCustomURLProtocol : NSURLProtocol @end @implementation IMYCustomURLProtocol +(void)load { [NSURLProtocol registerClass:self]; } + (BOOL)canInitWithRequest:(NSURLRequest *)request { NSString* urlString = request.URL.absoluteString; NSDictionary* dictionary = webViewReuqestMap[urlString]; if (dictionary) { [webViewRequestMap removeObjectForKey:urlString]; if ([request isKindOfClass:[NSMutableURLRequest class]]) { [(id)request setValue:@"HAHA" forHTTPHeaderField:@"MeiYou Co.,Ltd"]; } } return NO; } @end