// 注册拦截请求的 NSURLProtocol[NSURLProtocol registerClass:[MSDKDnsHttpMessageTools class]];// 需要设置 SNI 的 URLNSString *originalUrl = @"your url";NSURL *url = [NSURL URLWithString:originalUrl];NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];NSArray *result = [[MSDKDns sharedInstance] WGGetHostByName:url.host];NSString *ip = nil;if (result && result.count > 1) {if (![result[1] isEqualToString:@"0"]) {ip = result[1];} else {ip = result[0];}}// 通过 HTTPDNS 获取 IP 成功,进行 URL 替换和 HOST 头设置if (ip) {NSRange hostFirstRange = [originalUrl rangeOfString:url.host];if (NSNotFound != hostFirstRange.location) {NSString *newUrl = [originalUrl stringByReplacingCharactersInRange:hostFirstRange withString:ip];request.URL = [NSURL URLWithString:newUrl];[request setValue:url.host forHTTPHeaderField:@"host"];}}// NSURLConnection 例子self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];[self.connection start];// NSURLSession 例子NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];NSArray *protocolArray = @[ [MSDKDnsHttpMessageTools class] ];configuration.protocolClasses = protocolArray;NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];self.task = [session dataTaskWithRequest:request];[self.task resume];// 注*:使用 NSURLProtocol 拦截 NSURLSession 发起的 POST 请求时,HTTPBody 为空。// 解决方案有两个:// 1. 使用 NSURLConnection 发 POST 请求。// 2. 先将 HTTPBody 放入 HTTP Header field 中,然后在 NSURLProtocol 中再取出来。// 下面主要演示第二种解决方案// NSString *postStr = [NSString stringWithFormat:@"param1=%@¶m2=%@", @"val1", @"val2"];// [_request addValue:postStr forHTTPHeaderField:@"originalBody"];// _request.HTTPMethod = @"POST";// NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];// NSArray *protocolArray = @[ [CFHttpMessageURLProtocol class] ];// configuration.protocolClasses = protocolArray;// NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];// NSURLSessionTask *task = [session dataTaskWithRequest:_request];// [task resume];
#pragma mark - SNI 场景,仅调用一次即可,请勿多次调用/**SNI 场景下设置需要拦截的域名列表建议使用该接口设置,仅拦截 SNI 场景下的域名,避免拦截其它场景下的域名@param hijackDomainArray 需要拦截的域名列表*/- (void) WGSetHijackDomainArray:(NSArray *)hijackDomainArray;/**SNI 场景下设置不需要拦截的域名列表@param noHijackDomainArray 不需要拦截的域名列表*/- (void) WGSetNoHijackDomainArray:(NSArray *)noHijackDomainArray;
本页内容是否解决了您的问题?