You need to enable JavaScript to run this app.
导航

原生 NSURLProtocol

最近更新时间2023.06.21 19:27:08

首次发布时间2023.03.22 20:49:16

方案描述

如果您的 app 使用网络库(NSURLSessionAFNetworkingAlamoFire)发送网络请求,而且您没有自定义 NSURLProtocol,您可以配置 NSURLSession 使用 MNet Protocol。MNet Protocol 可以自动拦截 NSURLSession 中的请求。然后,您可以使用网络库发送被拦截的请求。

自 0.11.1 版本起,HTTPDNS iOS SDK 支持 MNet Protocol。MNet Protocol 是 HTTPDNS iOS SDK 基于 NSURLProtocol 封装的 Protocol。MNet Protocol 继承了 NSURLProtocol,可以自动拦截 NSURLSession 中的请求。MNet Protocol 解决了自定义 NSURLProtocol 使用的 CFNetwork 库功能受限,扩展性差的问题。

App 开启代理时,您的 app 仍然可以通过该集成方案发送和接收请求,但是 SDK 只返回 Local DNS 的解析结果。

前提条件

实现步骤

注意

为了演示需要,示例代码仅提供了集成方案中最基本的逻辑。移动解析 HTTPDNS 仅保证 HTTPDNS SDK 本身的 可用性。在生产环境下,您需要自行保证集成方案的健壮性。

  1. 通过 TTHttpMnetURLProtocol 接口加载 MNet Protocol。然后,您可以配置 NSURLSession 使用 MNet Protocol。

    // 配置 sharedSession 使用 MNet Protocol
    [NSURLProtocol registerClass:[TTHttpMnetURLProtocol class]];
    NSURLSession* myHttpDnsSession = [NSURLSession sharedSession];
    
  2. 使用您的网络库(NSURLSession、AFNetworking 或 AlamoFire)发送请求。

    // 使用 NSURLSession 网络库发送请求
    NSURLSession* session = myHttpDnsSession;
    [[session dataTaskWithRequest:request completionHandler:^(NSData* _Nullable data, NSURLResponse* _Nullable response, NSError* _Nullable error) {
         NSLog(@"request error is %@",error);
         if (!error) {
             NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
             [[BDDnsCookieManager sharedInstance] parseHeaderFields:httpResponse.allHeaderFields forURL:originUrl];
             responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
             [self.class logOutput:responseString isNSLog:YES isLogWindow:NO];
         }
     }] resume];
    
    // 使用 AFNetworking 网络库转发请求
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    
    AFHTTPSessionManager* sessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:config];
      
    NSURLSessionDataTask* task =
      [sessionManager dataTaskWithHTTPMethod:@"Get"
                                   URLString:@"https://www.toutiao.com"
                                  parameters:nil
                                     headers:nil
      uploadProgress:^(NSProgress * _Nonnull uploadProgress) { 
    
            ......
    
      }];
    [task resume];
    
    // 使用 AlamoFire 网络库转发请求
    let configuration = URLSessionConfiguration.default
    configuration.httpAdditionalHeaders = Alamofire.SessionManager.defaultHTTPHeaders
    sessionManager = Alamofire.SessionManager(configuration: configuration)
    
    TTSwiftRequestTest.shared.sessionManager.request("https://www.toutiao.com").response { response in
              debugPrint(response.response?.statusCode ?? -1)
    }