AFNetworking 保存Cookie Session 和 Webview 共享Cookie

1, 请求并携带SessionId, 代码如下:

 

//当请求成共后调用如下代码, 保存Cookie
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL: [NSURL URLWithString:kServerAddress]];  
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:cookies];  
[[NSUserDefaults standardUserDefaults] setObject:data forKey:kUserDefaultsCookie]; 

 

 

 

//请求前,设置上次保存的Cookie
NSData *cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:kUserDefaultsCookie];  
if([cookiesdata length]) {  
  NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];  
  NSHTTPCookie *cookie;  
    for (cookie in cookies) {  
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];  
  }  
} 

通过以上设置, 使用 UIWebView loadRequest 方法load NSURLRequest 可以共用 Cookie.

2, 另一个版本:

  NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage]cookies];  
      
  NSString *signature = @"";  
  NSString *userId = @"";  
  NSString *JSESSIONID = @"";  
  for (NSHTTPCookie *cookie in cookies) {  
    if ([cookie.name isEqualToString:@"JSESSIONID"]) {  
      JSESSIONID = cookie.value;  
    }  
    //其他Cookie值 
  }  
  NSString *cookieStr = [NSString stringWithFormat:@"JSESSIONID=%@;...",JSESSIONID,..];  
  [manager.requestSerializer setValue:cookieStr forHTTPHeaderField:@"Cookie"];

 

posted @ 2015-05-21 14:53  TuWei  阅读(2245)  评论(0编辑  收藏  举报