使用NSURLSession進(jìn)行重定向

使用URLSession進(jìn)行重定向

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);
    
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容