UIWebView设置request参数

一、设置header

//self.customHeaders 是你需要的header的字典
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    BOOL headerIsPresent = [[request allHTTPHeaderFields] objectForKey:@"myCustomHeader"]!=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];
             for(NSString *key in [self.customHeaders allKeys]){
                    [request addValue:[self.customHeaders objectForKey:key] forHTTPHeaderField:key];
                }
            [webView loadRequest:request];
        });
    });
    return NO;
}

二、设置user-agent

NSDictionary *dictionnary = @{
  @"UserAgent":@"myUserAgent"
};
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];
[[NSUserDefaults standardUserDefaults] synchronize];

你可能感兴趣的:(UIWebView设置request参数)