一直覺得ios的http請求這塊很簡單應該不支持記錄,保存,或者使用cookie,但是想固然歸想固然,真用的時候,真研究了一下發現還真強大。通過一番的研究簡單說一下個人理解:當你訪問一個網站時,無論你願意或者不肯意,NSURLRequest都會幫你主動記錄下來你訪問的站點設置的cookie,並且很負責任的,當你下次再訪問這個站點時,NSURLRequest會拿着上次保存下來了的cookie繼續去請求。這規律一樣適用於ASIHTTPRequest。因此當你作一些基於認證的網絡請求時,cookie不失爲一個完美的解決方案。ios
那麼怎麼查看cookie呢?很簡單:web
1
2 3 4 |
NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *cookie in [cookieJar cookies]) { NSLog(@"%@", cookie); } |
這樣就列出了全部已保存的cookie,若是當前爲空怎麼辦呢?隨便請求一個url嘍。cookie
1
2 3 4 5 6 7 8 9 10 11 12 |
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://blog.cnrainbird.com"]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:3]; [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage]; for (NSHTTPCookie *cookie in [cookieJar cookies]) { NSLog(@"%@", cookie); } |
是否是獲得了相似:網絡
1
|
<NSHTTPCookie version:0 name:"PHPSESSID" value:"evf5rcboo8th1dnl53fs4ukmt2" expiresDate:(null) created:2012-03-13 14:28:13 +0000 (3.53342e+08) sessionOnly:TRUE domain:"blog.cnrainbird.com" path:"/" isSecure:FALSE>
|
的東東?這就是cookie啦session
怎麼清空cookie呢?dom
1
2 3 4 5 |
NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray *_tmpArray = [NSArray arrayWithArray:[cookieJar cookies]]; for (id obj in _tmpArray) { [cookieJar deleteCookie:obj]; } |
這樣cookie就消失的一乾二淨了。ide
會查看cookie了,也會清空cookie了,怎麼設置指定的cookie呢?網站
1
2 3 4 5 6 7 8 9 10 |
NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
[cookieProperties setObject:@"username" forKey:NSHTTPCookieName]; [cookieProperties setObject:@"rainbird" forKey:NSHTTPCookieValue]; [cookieProperties setObject:@"cnrainbird.com" forKey:NSHTTPCookieDomain]; [cookieProperties setObject:@"cnrainbird.com" forKey:NSHTTPCookieOriginURL]; [cookieProperties setObject:@"/" forKey:NSHTTPCookiePath]; [cookieProperties setObject:@"0" forKey:NSHTTPCookieVersion]; NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties]; [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie]; |
這樣就能夠了。輸入一下,是否是獲得了下面這樣的結果:url
1
|
<NSHTTPCookie version:0 name:"username" value:"rainbird" expiresDate:(null) created:2012-03-13 14:36:53 +0000 (3.53342e+08) sessionOnly:TRUE domain:"cnrainbird.com" path:"/" isSecure:FALSE>
|
其實ios的cookie就這麼簡單。若是mac也支持這麼幹的話,那之後寫點登錄的腳本不是簡單多了:)spa