iOS11 之前的处理方法:NSURLProtocal拦截后,手动管理 Cookie 的存储:
步骤:做 IP 替换时将原始 URL 保存到 Header 中
- + (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
- NSMutableURLRequest *mutableReq = [request mutableCopy];
- NSString *originalUrl = mutableReq.URL.absoluteString;
- NSURL *url = [NSURL URLWithString:originalUrl];
- // 异步接口获取IP地址
- NSString *ip = [[HttpDnsService sharedInstance] getIpByHostAsync:url.host];
- if (ip) {
- NSRange hostFirstRange = [originalUrl rangeOfString:url.host];
- if (NSNotFound != hostFirstRange.location) {
- NSString *newUrl = [originalUrl stringByReplacingCharactersInRange:hostFirstRange withString:ip];
- mutableReq.URL = [NSURL URLWithString:newUrl];
- [mutableReq setValue:url.host forHTTPHeaderField:@"host"];
- // 添加originalUrl保存原始URL
- [mutableReq addValue:originalUrl forHTTPHeaderField:@"originalUrl"];
- }
- }
- NSURLRequest *postRequestIncludeBody = [mutableReq cyl_getPostRequestIncludeBody];
- return postRequestIncludeBody;
- }
然后获取到数据后,手动管理 Cookie:
- - (void)handleCookiesFromResponse:(NSURLResponse *)response {
- NSString *originalURLString = [self.request valueForHTTPHeaderField:@"originalUrl"];
- if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
- NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
- NSDictionary<NSString *, NSString *> *allHeaderFields = httpResponse.allHeaderFields;
- if (originalURLString && originalURLString.length > 0) {
- NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:allHeaderFields forURL: [[NSURL alloc] initWithString:originalURLString]];
- if (cookies && cookies.count > 0) {
- NSURL *originalURL = [NSURL URLWithString:originalURLString];
- [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:cookies forURL:originalURL mainDocumentURL:nil];
- }
- }
- }
- }
- - (void)task:(CFHTTPDNSRequestTask *)task didReceiveResponse:(NSURLResponse *)response cachePolicy:(NSURLCacheStoragePolicy)cachePolicy {
- [self handleCookiesFromResponse:response];
- [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:cachePolicy];
- }
发送请求前,向请求中添加Cookie信息:
- + (void)handleCookieWithRequest:(NSMutableURLRequest *)request {
- NSString* originalURLString = [request valueForHTTPHeaderField:@"originalUrl"];
- if (!originalURLString || originalURLString.length == 0) {
- return;
- }
- NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
- if (cookies && cookies.count >0) {
- NSDictionary *cookieHeaders = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
- NSString *cookieString = [cookieHeaders objectForKey:@"Cookie"];
- [request addValue:cookieString forHTTPHeaderField:@"Cookie"];
- }
- }
- + (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
- NSMutableURLRequest *mutableReq = [request mutableCopy];
- //...
- [self handleCookieWithRequest:mutableReq];
- return [mutableReq copy];
- }