建立请求,设置HTTPHeaderField各参数,通过NSURLSessionTask发送请求。
我们封装的AFNetworking组件只能传递参数,不能设置HTTPHeaderField参数,必定发送带HTTPHeaderField参数的请求在少数,不想再修改组件库了。就想到下面间断发送带cookie等HTTPHeaderField参数的请求。我们使用的ReactiveCocoa组件,所以对block的处理采用的是它自带的@weakify(self);和@strongify(self);。若自己ReactiveCocoa,自己找block弱引用的方法,这里就不多说了。
//判断字符串是否为空 #define isEmptyString(str) ([str isKindOfClass:[NSNull class]] || str == nil || ![str isKindOfClass:[NSString class]] || [str length] < 1) - (void)sendCookieRequestWithUrlString:(NSString *)urlString imageBlock:(void(^)(NSError *error))block { if(isEmptyString(urlString)) { if (block) { block([NSError errorWithDomain:@"请求地址为空" code:-1 userInfo:nil]); } return; } @weakify(self); //若想发送同步消息只需要注释下面一行代码和});就可以 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ @strongify(self); NSURL * url = [NSURL URLWithString:urlString]; NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url]; NSURLSession * session = [NSURLSession sharedSession]; NSString *cookie = [self readCurrentCookieWithDomain:urlString]; [request addValue:cookie forHTTPHeaderField:@"Cookie"]; // 发送请求 NSURLSessionTask * sessionTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (error) { if (block) { block(error); } return; } NSString *mmmmmmm = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"mmmmmmm: %@, response:%@, error:%@, request.allHTTPHeaderFields:%@", mmmmmmm, response, error, request.allHTTPHeaderFields); if (block) { block(nil); } }]; [sessionTask resume]; }); } //WKWebView的cookie文件中cookie是针对app所有的网址,传递过来请求的地址也没有用 - (NSString *)readCurrentCookieWithDomain:(NSString *)domainStr{ NSHTTPCookieStorage*cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage]; NSMutableString * cookieString = [[NSMutableString alloc]init]; for (NSHTTPCookie*cookie in [cookieJar cookies]) { [cookieString appendFormat:@"%@=%@;",cookie.name,cookie.value]; } //删除最后一个“;” [cookieString deleteCharactersInRange:NSMakeRange(cookieString.length - 1, 1)]; return cookieString; }