AFnetworking框架儲存cookie和使用cookie請求總結
阿新 • • 發佈:2019-01-26
從response的HeaderField獲得標頭檔案,從標頭檔案中通過NSHTTPCookie的cookiesWithResponseHeaderFields組成cookie的NSArray,將生成cookie的array,使用NSHttpCookie的reqeustHeaderFieldsWithCookies方法拼接成合法的http header field。最後set到request中即可。
[manager.requestSerializer setValue:[requestFields objectForKey:@"Cookie"] forHTTPHeaderField:@"Cookie"];
使用以下程式碼進行請求,解析為cookie存入NSUserDefaults,全域性單例類
在要使用時,從[NSUserDefaults standardUserDefaults]中取出,使用AFHTTPRequestOperationManager的[manager.requestSerializer setValue: forHTTPHeaderField:];對NSMutableRequest的headerField中的cookie進行賦值。[manager POST:requestUrl parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) { /** * 從response的HeaderField獲得標頭檔案,從標頭檔案中通過NSHTTPCookie的cookiesWithResponseHeaderFields組成cookie的NSArray,將生成cookie的array,使用NSHttpCookie的reqeustHeaderFieldsWithCookies方法拼接成合法的http header field。最後set到request中即可。 [manager.requestSerializer setValue:[requestFields objectForKey:@"Cookie"] forHTTPHeaderField:@"Cookie"]; */ NSDictionary *fields= [operation.response allHeaderFields]; NSArray *cookies=[NSHTTPCookie cookiesWithResponseHeaderFields:fields forURL:[NSURL URLWithString:BaseURLString]]; NSDictionary* requestFields=[NSHTTPCookie requestHeaderFieldsWithCookies:cookies]; [[NSUserDefaults standardUserDefaults] setObject:[requestFields objectForKey:@"Cookie"] forKey:mUserDefaultsCookie]; // 使用jsonkit進行json解析 int result=[self jsonToUserDefault:operation]; } failure:^(AFHTTPRequestOperation *operation, NSError *error) { DLog(@"Error: %@", error); // 使用Bl的 loginfailed方法 [_delegate loginFail]; }];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; manager.responseSerializer = [AFJSONResponseSerializer serializer]; [manager.requestSerializer setValue: [[NSUserDefaults standardUserDefaults] objectForKey:mUserDefaultsCookie]forHTTPHeaderField:@"Cookie"]; manager.responseSerializer.acceptableContentTypes=[NSSet setWithObject:@"text/html"]; NSString* suffix=[NSString stringWithFormat:@"?m=user&a=edit&nickname=%@&age=%@",nickName,age]; NSString* requestUrl =[BaseURLString stringByAppendingString:suffix]; NSString* utf8=[requestUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//將請求地址轉換為utf8編碼,使用預設unicode進行請求會報編碼錯誤