AFNetworking 支持cookies的解决方案
???AFNetworking是支持cookies,只不過它把這個(gè)邏輯交給了iOS 底層的api處理了。
? ?多話不說了,很討厭網(wǎng)上那些人云亦云的帖子,三人成虎!
? 本次我們的項(xiàng)目重構(gòu),需要用到cookies,我直接給出解決方案吧:
(cookie使用支持的簡單思路是:首次請(qǐng)求時(shí),服務(wù)器取回cookies,然后每次請(qǐng)求時(shí)附加上cookie,如此反復(fù)即可,至于cookies中有啥內(nèi)容,我們不用關(guān)注,服務(wù)器要就給她)
??我使用的是AFNetworking的AFHTTPClient進(jìn)行網(wǎng)絡(luò)訪問的,我就直接在AFHTTPClient.h添加兩個(gè)支持cookies的方法,一個(gè)是為post寫的,另一個(gè)是為get寫的。
1、在AFHTTPClient.h添加兩個(gè)支持cookies的方法,每次請(qǐng)求時(shí),都發(fā)送出本地cookies
| 12345 | ?//?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; |
| 12345 | //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; |
? ?其實(shí)現(xiàn)是:
| 1234567891011121314151617181920212223242526272829303132333435363738394041 | -?(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實(shí)現(xiàn)是:
| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 | -?(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];? } |
? 對(duì)應(yīng)的使用方法分別是:
2、每次請(qǐng)求返回時(shí),保存cookie,以供以后使用
?get的使用方式:
?| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 | /**?*執(zhí)行g(shù)et請(qǐng)求,支持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的使用方式如下:
?| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 | /**?*執(zhí)行post請(qǐng)求:支持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);?????????}???????????????}];??????????} |
測試運(yùn)行:
?| 123456 | 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>//--使用cookiesTPTripPlusDetailViewController.m:141??? ??....?開始請(qǐng)求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> |
從結(jié)果可看出,完美運(yùn)行。
總結(jié)
以上是生活随笔為你收集整理的AFNetworking 支持cookies的解决方案的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 对话南科大沈平:在人工智能开源中,高校能
- 下一篇: ker矩阵是什么意思_重做第一次作业(矩