【已过时,新的sdk和框架默认支持】AFNetworking 支持cookies的解决方案
【已过时,新的sdk和框架默认支持】AFNetworking 支持cookies的解决方案
法斗斗 发表于2年前
【已过时,新的sdk和框架默认支持】AFNetworking 支持cookies的解决方案
  • 发表于 2年前
  • 阅读 13
  • 收藏 0
  • 点赞 2
  • 评论 0

腾讯云 新注册用户 域名抢购1元起>>>   

【已过时,新的sdk和框架默认支持】AFNetworking 支持cookies的解决方案

摘要 AFNetworking是支持cookies,只不过它把这个逻辑交给了iOS 底层的api处理了。 Cookies are handled entirely by the Foundation URL Loading system, upon which AFNetworking is built. You have complete control over the behavior of cookies in requests by configuring NSMutableURLRequest (setHTTPShouldHandleCookies) and NSHTTPCoo...

   AFNetworking是支持cookies,只不过它把这个逻辑交给了iOS 底层的api处理了。

   多话不说了,很讨厌网上那些人云亦云的帖子,三人成虎!

  本次我们的项目重构,需要用到cookies,我直接给出解决方案吧:

(cookie使用支持的简单思路是:首次请求时,服务器取回cookies,然后每次请求时附加上cookie,如此反复即可,至于cookies中有啥内容,我们不用关注,服务器要就给她)

  我使用的是AFNetworking的AFHTTPClient进行网络访问的,我就直接在AFHTTPClient.h添加两个支持cookies的方法,一个是为post写的,另一个是为get写的。

1、在AFHTTPClient.h添加两个支持cookies的方法,每次请求时,都发送出本地cookies

 // add by block cheng
- (void)blockGetPath:(NSString *)path
     parameters:(NSDictionary *)parameters
        success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;

 

//add by block cheng
- (void)blockPostPath:(NSString *)path
      parameters:(NSDictionary *)parameters
         success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
         failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;

 

   其实现是:

- (void)blockGetPath:(NSString *)path
          parameters:(NSDictionary *)parameters
             success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
             failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    
    if (!path) {
        path = @"";
    }
    
    NSArray *arcCookies = [NSKeyedUnarchiver unarchiveObjectWithData: [[NSUserDefaults standardUserDefaults] objectForKey: @"sessionCookies"]];
    NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    
    for (NSHTTPCookie *cookie in arcCookies){
        [cookieStorage setCookie: cookie];
    }
    
    NSURL *dataUrl = [NSURL URLWithString:path relativeToURL:self.baseURL];
    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:dataUrl];//id: NSHTTPCookie
    NSDictionary *sheaders = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
    
    NSString *charset = (NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    
    __strong NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:dataUrl cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.f];
    
    [request setHTTPMethod:@"GET"];
    [request addValue:@"iOS" forHTTPHeaderField:@"User-Agent"];
    [request setValue:[NSString stringWithFormat:@"application/x-www-form-urlencoded; charset=%@", charset] forHTTPHeaderField:@"Content-Type"];
//    [request setHTTPBody:[AFQueryStringFromParametersWithEncoding(parameters, NSUTF8StringEncoding) dataUsingEncoding:NSUTF8StringEncoding]];
    [request setAllHTTPHeaderFields:sheaders];

    
    if (parameters) {
            dataUrl = [NSURL URLWithString:[[dataUrl absoluteString] stringByAppendingFormat:[path rangeOfString:@"?"].location == NSNotFound ? @"?%@" : @"&%@", AFQueryStringFromParametersWithEncoding(parameters, self.stringEncoding)]];
            [request setURL:dataUrl];
    }
    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
    [self enqueueHTTPRequestOperation:operation];


}

 

  post实现是:

- (void)blockPostPath:(NSString *)path
           parameters:(NSDictionary *)parameters
              success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
              failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    if (!path) {
        path = @"";
    }
    NSArray *arcCookies = [NSKeyedUnarchiver unarchiveObjectWithData: [[NSUserDefaults standardUserDefaults] objectForKey: @"sessionCookies"]];
    NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    
    for (NSHTTPCookie *cookie in arcCookies){
        [cookieStorage setCookie: cookie];
    }
    
    NSURL *dataUrl = [NSURL URLWithString:path relativeToURL:self.baseURL];
    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:dataUrl];//id: NSHTTPCookie
    NSDictionary *sheaders = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
    
    NSString *charset = (NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    
    __strong NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:dataUrl cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.f];
    
    [request setHTTPMethod:@"Post"];
    [request addValue:@"iOS" forHTTPHeaderField:@"User-Agent"];
    [request setValue:[NSString stringWithFormat:@"application/x-www-form-urlencoded; charset=%@", charset] forHTTPHeaderField:@"Content-Type"];
//    [request setHTTPBody:[AFQueryStringFromParametersWithEncoding(parameters, NSUTF8StringEncoding) dataUsingEncoding:NSUTF8StringEncoding]];
    [request setAllHTTPHeaderFields:sheaders];

    if (parameters) {
        NSString *charset = (__bridge NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(self.stringEncoding));
        NSError *error = nil;
        
        switch (self.parameterEncoding) {
            case AFFormURLParameterEncoding:;
                [request setValue:[NSString stringWithFormat:@"application/x-www-form-urlencoded; charset=%@", charset] forHTTPHeaderField:@"Content-Type"];
                [request setHTTPBody:[AFQueryStringFromParametersWithEncoding(parameters, self.stringEncoding) dataUsingEncoding:self.stringEncoding]];
                break;
            case AFJSONParameterEncoding:;
                [request setValue:[NSString stringWithFormat:@"application/json; charset=%@", charset] forHTTPHeaderField:@"Content-Type"];
                [request setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:0 error:&error]];
                break;
            case AFPropertyListParameterEncoding:;
                [request setValue:[NSString stringWithFormat:@"application/x-plist; charset=%@", charset] forHTTPHeaderField:@"Content-Type"];
                [request setHTTPBody:[NSPropertyListSerialization dataWithPropertyList:parameters format:NSPropertyListXMLFormat_v1_0 options:0 error:&error]];
                break;
        }
        
        if (error) {
            NSLog(@"%@ %@: %@", [self class], NSStringFromSelector(_cmd), error);
        }
    
    }
    
    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
    [self enqueueHTTPRequestOperation:operation];	

}

 

  对应的使用方法分别是:

2、每次请求返回时,保存cookie,以供以后使用

 get的使用方式:

/**
 *执行get请求,支持cookie
 *TODO: 需要完善
 **/
-(void)asynchronousCookiesGET:(NSString *)path witParams:(NSMutableDictionary *)params
{
    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:BASE_URL_SESSION]];
    self.client = httpClient;
    [httpClient release];
    [self.client blockGetPath:path parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         D_END;
         LogNET(@"------------------------GET--->------------------------------");
         LogNET(@"netWorking url:: %@",operation.request.URL.absoluteString);
         LogNET(@"netWorking params:: %@",params);
         LogNET(@"net working statuCode:: %d",operation.response.statusCode);
         LogNET(@"net working responseString:: %@",operation.responseString);
         LogNET(@"------------------------GET---<-----------------------------");
         
         NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
         for (NSHTTPCookie *cookie in cookies) {
             // Here I see the correct rails session cookie
             NSLog(@"Block cookie: %@", cookie);
         }
         
         NSData *cookiesData = [NSKeyedArchiver archivedDataWithRootObject: [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]];
         NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
         [defaults setObject: cookiesData forKey: @"sessionCookies"];
         [defaults synchronize];
         
         
    //handle server return data;
         
         
         
     }failure:^(AFHTTPRequestOperation *operation, NSError* error)
     {
         LogNET(@"------------------------GET--->------------------------------");
         LogNET(@"netWorking url:: %@",operation.request.URL.absoluteString);
         LogNET(@"net working statuCode:: %d",operation.response.statusCode);
         LogNET(@"net working responseString:: %@",operation.responseString);
         LogNET(@"------------------------GET---<-----------------------------");
         
         WebExceptionEntity* exception = [[WebExceptionEntity alloc] initWithExceptionString:operation.responseString withStatusCode:operation.response.statusCode withError:error];
         self.webException= exception;
         [exception release];
         
         if (self.exceptionBlock)
         {
             self.exceptionBlock(self,self.webException);
         }
         
     }
     ];


    
    
}

 

Post的使用方式如下:

/**
 *执行post请求:支持cookie的版本
 **/
-(void)asynchronousCookiesPost:(NSString *)path
              witParams:(NSMutableDictionary *)params
{
    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:BASE_URL_SESSION]];
    self.client = httpClient;
    [httpClient release];
    if (self.preBlcok) {
        self.preBlcok(self);
    }
    [self.client blockPostPath:path parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         D_END;
         LogNET(@"------------------------POST--->------------------------------");
         LogNET(@"netWorking url:: %@",operation.request.URL.absoluteString);
         LogNET(@"netWorking params:: %@",params);
         LogNET(@"net working statuCode:: %d",operation.response.statusCode);
         LogNET(@"net working responseString:: %@",operation.responseString);
         LogNET(@"------------------------POST---<-----------------------------");
         
         NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
         for (NSHTTPCookie *cookie in cookies) {
             // Here I see the correct rails session cookie
             NSLog(@"cookie: %@", cookie);
         }
         
         NSData *cookiesData = [NSKeyedArchiver archivedDataWithRootObject: [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]];
         NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
         [defaults setObject: cookiesData forKey: @"sessionCookies"];
         [defaults synchronize];
    
         //handle server return data
     }failure:^(AFHTTPRequestOperation *operation, NSError* error)
     {
         LogNET(@"------------------------POST--->------------------------------");
         LogNET(@"netWorking url:: %@",operation.request.URL.absoluteString);
         LogNET(@"net working statuCode:: %d",operation.response.statusCode);
         LogNET(@"net working responseString:: %@",operation.responseString);
         LogNET(@"------------------------POST---<-----------------------------");
         WebExceptionEntity* exception = [[WebExceptionEntity alloc] initWithExceptionString:operation.responseString withStatusCode:operation.response.statusCode withError:error];
         self.webException= exception;
         [exception release];
         
         if (self.exceptionBlock)
         {
             self.exceptionBlock(self,self.webException);
         }
         
     }];
    
    
}

 

测试运行:

2014-02-14 10:00:53.465 TripPlus[15245:60b] cookie: <NSHTTPCookie version:0 name:"ssid" value:"79244stsh4p3shv1ftd1125d90" expiresDate:(null) created:2014-02-14 02:00:53 +0000 (4.14036e+08) sessionOnly:TRUE domain:"192.168.1.199" path:"/" isSecure:FALSE>

//--使用cookies
TPTripPlusDetailViewController.m:141	  .... 开始请求
AFHTTPClient.m:706	post  add cookie:<NSHTTPCookie version:0 name:"acb5f57bfaec0550abdb337d5e8f0f40" value:"1febc174d86a8f5473af180658a7d9369b1e35daa%3A4%3A%7Bi%3A0%3Bs%3A1%3A%221%22%3Bi%3A1%3Bs%3A17%3A%22test%40joviainc.com%22%3Bi%3A2%3Bi%3A2592000%3Bi%3A3%3Ba%3A0%3A%7B%7D%7D" expiresDate:2014-03-16 02:00:50 +0000 created:2001-01-01 00:00:01 +0000 (1) sessionOnly:FALSE domain:"192.168.1.199" path:"/" isSecure:FALSE>
AFHTTPClient.m:706	post  add cookie:<NSHTTPCookie version:0 name:"ssid" value:"79244stsh4p3shv1ftd1125d90" expiresDate:(null) created:2001-01-01 00:00:01 +0000 (1) sessionOnly:TRUE domain:"192.168.1.199" path:"/" isSecure:FALSE>

 

从结果可看出,完美运行。

由于项目结构复杂,我还没来得及花时间抽出好的完整代码,但关键代码都已经在上述代码中给出,需要的同学,自己整理下,有问题,可以联系我,3q

共有 人打赏支持
粉丝 21
博文 293
码字总数 6335
×
法斗斗
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: