1. 程式人生 > >iOS原生請求獲取Cookie值

iOS原生請求獲取Cookie值

header share httpurl logs fields head working cache net

 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值