Create the request, set the parameters of HTTPHeaderField, and send the request through NSURLSessionTask.
The AFNetworking component we encapsulate can only pass parameters, and can't set HTTPHeaderField parameters. There must be a few requests with HTTPHeaderField parameters sent, so we don't want to modify the component library any more. Think of the following intermittent requests with HTTPHeaderField parameters such as cookie s. We use the ReactiveCocoa component, so we use its own @ weakify(self); and @ strongify(self);. If you ReactiveCocoa and find the weak reference method of the block, you won't talk about it here.
//Judge whether the string is empty
#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:@"Request address is empty" code:-1 userInfo:nil]);
}
return;
}
@weakify(self);
//If you want to send a synchronization message, just comment the following line of code and}); you can
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"];
// Send request
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];
});
}
//In the cookie file of WKWebView, the cookie is for all the URLs of the app, and the address passed in the request is useless
- (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];
}
//Delete last ';'
[cookieString deleteCharactersInRange:NSMakeRange(cookieString.length - 1, 1)];
return cookieString;
}