iOS開發ASIHTTPRequest中Cookie的使用

來源:互聯網
上載者:User

本文為大家介紹了iOS開發ASIHTTPRequest中Cookie的使用的內容,其中包括持久化cookie,自己處理cookie等等內容,希望對大家有所協助。

持久化cookie

ASIHTTPRequest允許你使用全域儲存來和所有使用CFNetwork或者NSURLRequest介面的程式共用cookie。

如果設定useCookiePersistence為YES預設值),cookie會被儲存在共用的 NSHTTPCookieStorage 容器中,並且會自動被其他request重用。值得一提的是,ASIHTTPRequest會向伺服器發送其他程式建立的cookie如果這些cookie對特定request有效話)。

你可以清空session期間建立的所有cookie:

 
  1. [ASIHTTPRequest setSessionCookies:nil]; 

這裡的‘session cookies’指的是一個session中建立的所有cookie,而非沒有到期時間的cookie即通常所指的會話cookie,這種cookie會在程式結束時被清除)。

另外,有個方便的函數 clearSession可以清除session期間產生的所有的cookie和緩衝的授權資料。 

自己處理cookie

如果你願意,你大可以關閉useCookiePersistence,自己來管理某個request的一系列cookie:

 
  1. //建立一個cookie 
  2. NSDictionary *properties = [[[NSMutableDictionary alloc] init] autorelease]; 
  3. [properties setValue:[@"Test Value" encodedCookieValue] forKey:NSHTTPCookieValue]; 
  4. [properties setValue:@"ASIHTTPRequestTestCookie" forKey:NSHTTPCookieName]; 
  5. [properties setValue:@".dreamingwish.com" forKey:NSHTTPCookieDomain]; 
  6. [properties setValue:[NSDate dateWithTimeIntervalSinceNow:60*60] forKey:NSHTTPCookieExpires]; 
  7. [properties setValue:@"/asi-http-request/tests" forKey:NSHTTPCookiePath]; 
  8. NSHTTPCookie *cookie = [[[NSHTTPCookie alloc] initWithProperties:properties] autorelease]; 
  9.  
  10. //這個url會返回名為'ASIHTTPRequestTestCookie'的cookie的值 
  11. url = [NSURL URLWithString:@"http://www.dreamingwish.com/"]; 
  12. request = [ASIHTTPRequest requestWithURL:url]; 
  13. [request setUseCookiePersistence:NO]; 
  14. [request setRequestCookies:[NSMutableArray arrayWithObject:cookie]]; 
  15. [request startSynchronous]; 
  16.  
  17. //將會列印: I have 'Test Value' as the value of 'ASIHTTPRequestTestCookie' 
  18. NSLog(@"%@",[request responseString]); 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.