如何为UIWebView中加载的所有请求设置http标头?

时间:2014-12-22 05:40:02

标签: ios objective-c uiwebview user-agent nsurlrequest

我尝试了以下内容:

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

    NSLog([request valueForHTTPHeaderField:@"User-Agent"]);    

    if ([[request valueForHTTPHeaderField:@"User-Agent"] isEqualToString:@"CustomName"]) {
        return YES;
    }
    else {
        NSMutableURLRequest *mutable_request= [request mutableCopy];
        [mutable_request setValue:@"CustomName" forHTTPHeaderField:@"User-Agent"];
        request = [mutable_request copy];
        [self.web loadRequest:request];
        return NO;
    }
}

我甚至在viewDidLoad()方法中添加了以下代码行:

NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"CustomName",@"User-Agent", nil];  
[[NSUserDefaults standardUserDefaults] registerDefaults:dict];

然而,每当我尝试使用[self.web loadRequest:request]加载请求时,它都会进入无限循环并且HTTPHeaderField的值为#34; User-Agent"始终打印为

"Mozilla/5.0 (iPhone; CPU iPhone OS 10_10_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Mobile/12B411" 

而不是" CustomName"。

2 个答案:

答案 0 :(得分:0)

NSLog(@" web url to load : %@",urlToLoad);
    NSMutableURLRequest *requestObj = [NSMutableURLRequest requestWithURL:urlToLoad];
    [requestObj setValue:[NSString stringWithFormat:@"%@ Safari/528.16", [requestObj valueForHTTPHeaderField:@"User-Agent"]] forHTTPHeaderField:@"User_Agent"];
    requestObj.timeoutInterval = 120;//Request Timeout interval added for request
    [requestObj setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];//added for removing cache data of webView
    [webview loadRequest:requestObj];

答案 1 :(得分:0)

我找到了答案,我不得不更换HTTPHeader" User-Agent"到" UserAgent"。 删除连字符( - )对我有用。

将以下方法添加到我的AppDelegate.h也有效

+ (void)initialize {
NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:@"CustomName", @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];

}