使用NSURLSession进行重定向

使用URLSession进行重定向

NSURL *url = [NSURL URLWithString:@"http://c.snnd.co/api/v4/click?campaign_id=4410534&publisher_id=52&rt=170401034908&_po=4f6801b69d272e96bbb920659a2f805b&_mw=p&_c=972&_cw=c&_ad=1288&publisher_slot=260&sub_1=pst2977485&pub_gaid=&pub_idfa=ADB6E76C-6B91-455B-81BE-DB884CC17818&pub_aid=&sub_2=695-669-773_33_0.300_20131822574410534260_iOS_1491019272&sub_3=Y29tLmdtZWRhbC5nb2xkZ21lZGFsKG5hdDMp_US_hcvr.ecpm5_i-1.5.3___ADB6E76C-6B91-455B-81BE-DB884CC17818&ch=pst"];
NSMutableURLRequest *quest = [NSMutableURLRequest requestWithURL:url];
quest.HTTPMethod = @"GET";
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
NSURLSession *urlSession = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue currentQueue]];
NSURLSessionDataTask *task = [urlSession dataTaskWithRequest:quest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
   NSHTTPURLResponse *urlResponse = (NSHTTPURLResponse *)response;
   NSLog(@"%ld",urlResponse.statusCode);
   NSLog(@"%@",urlResponse.allHeaderFields);
   NSDictionary *dic = urlResponse.allHeaderFields;
   NSLog(@"%@",dic[@"Location"]);
}];
[task resume];

遵守代理如下,completionHandler(nil)则拦截重定向;

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
willPerformHTTPRedirection:(NSHTTPURLResponse *)response
        newRequest:(NSURLRequest *)request
 completionHandler:(void (^)(NSURLRequest * __nullable))completionHandler{
    NSHTTPURLResponse *urlResponse = (NSHTTPURLResponse *)response;
    NSLog(@"%ld",urlResponse.statusCode);
    NSLog(@"%@",urlResponse.allHeaderFields);
    
    NSDictionary *dic = urlResponse.allHeaderFields;
    NSLog(@"%@",dic[@"Location"]);
    completionHandler(request);
    
}

你可能感兴趣的:(使用NSURLSession进行重定向)