iOS原生请求获取Cookie值

Posted absty_guo

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS原生请求获取Cookie值相关的知识,希望对你有一定的参考价值。

 1     //创建URL
 2     NSURL * url = [NSURL URLWithString:@"http://api.skyfox.org/api-test.php"];
 3     
 4     //创建request请求
 5     NSURLRequest * request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:3];
 6     
 7     //初始化请求队列
 8     NSOperationQueue *queue = [NSOperationQueue mainQueue];
 9     
10     [NSURLConnection sendAsynchronousRequest:request
11                                        queue:queue
12                            completionHandler:
13      ^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
14          
15          //转换NSURLResponse成为HTTPResponse
16          NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
17          
18          //获取headerfields
19          
20          //原生NSURLConnection写法
21          NSDictionary *fields = [httpResponse allHeaderFields];
22          
23          //afnetworking写法
24          //NSDictionary *fields = [operation.response allHeaderFields];
25          
26          
27          //获取cookie方法1
28          NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:fields forURL:url];
29       
30          for (NSHTTPCookie * cookie in cookies) {
31              
32              NSDictionary * cookieDic = [cookie properties];
33              NSLog(@"%@",cookieDic);
34          }
35          
36          //获取cookie方法2
37          /*
38           NSString *cookieString = [[HTTPResponse allHeaderFields] valueForKey:@"Set-Cookie"];
39           */
40          
41          
42          //获取cookie方法3
43          /*
44           NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
45           
46           for (NSHTTPCookie *cookie in [cookieJar cookies])
47           {
48           NSLog(@"cookie%@", cookie);
49           }
50           */
51     }];

 

以上是关于iOS原生请求获取Cookie值的主要内容,如果未能解决你的问题,请参考以下文章

纯js 原生JavaScript 设置 获取 cookie值

IOS UIWebView添加Cookie值请求

如何获取 cookie 并将它们用于其他请求,如 POST ( iOS )?

js代码片段: utils/lcoalStorage/cookie

用C#破解Chrome浏览器cookie值

iOS cookie的用法