参考文章:
URLProtocol 注册方式的细节问题
NSURLProtocol的基本使用
NSURLProtocol registerClass:
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"data.length:%ld",data.length);
}] resume];
[NSURLSession sharedSession]
会按照NSURLProtocol registerClass:注册的类遍历,后注册的先遍历.(只有一个可以接受响应)
NSURLSessionConfiguration.protocolClasses
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.protocolClasses = @[[WYTURLProtocol class]];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
[[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"data.length:%ld",data.length);
}] resume];
[NSURLSessionConfiguration defaultSessionConfiguration]
创建的config不受NSURLProtocol registerClass:注册的影响,需要配置config.protocolClasses
支持后台下载的session,不支持配置WYTURLProtocol
NSURLSessionConfiguration *config = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"NSURLProtocol_Test"];
// Custom NSURLProtocol subclasses are not available to background sessions.
// 支持后台下载的session,不支持配置WYTURLProtocol,设置protocolClasses不会生效
config.protocolClasses = @[[WYTURLProtocol class]];
HTTPBody丢失问题
据苹果官方说明,因为请求参数可能会很大,为了保证性能,请求参数是没有被拦截掉的,就是post的HTTPBody是没有的