iOS webView加载网页失败,浏览器成功的原因,以及读取cookie

开发过程中,使用UIWebView加载电脑版网页,登录出错,

请求头有误,webView请求头为:

User-Agent: Mozilla/5.0 (iPad; CPU OS 7_0_2 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Mobile/11A501


safari浏览器请求头为:

User-Agent: Mozilla/5.0 (iPad; CPU OS 7_0_2 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A501 Safari/9537.53

解决办法:

在webView加载之前执行下面代码

 NSString *userAgent = [_webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];

 userAgent = [userAgent stringByAppendingString:@" Version/7.0 Safari/9537.53"];

 [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent": userAgent}];


读取cookie方法:

 NSHTTPCookieStorage *sharedHTTPCookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];

 NSArray *cookies = [sharedHTTPCookieStorage cookiesForURL:request.URL];

 NSEnumerator *enumerator = [cookies objectEnumerator];

 NSHTTPCookie *cookie;

 while (cookie = [enumerator nextObject]) {

     NSLog(@"COOKIE{name: %@, value: %@}", [cookie name], [cookie value]);

 }



你可能感兴趣的:(功能)