NSURLProtocol 使用笔记,注意事项

作者 : 开心源码 本文共4886个字,预计阅读时间需要13分钟 发布时间: 2022-05-12 共127人阅读

初衷是为了让 UIWebView 可以阻拦 Ajax 请求。研究了一番找到了 NSURLProtocol。

URL loading system 结构图

NSURLProtocol 是属于 Foundation 框架里的 URL Loading System 的一部分,它是一个笼统类,不能去实例化它,只能子类化NSURLProtocol,而后使用的时候注册子类。一个相对晦涩难解的类。

那么假如开发者自己设置的一个 NSURLProtocol 并且注册到 app 中,那么在这个自己设置的 NSURLProtocol 中我们可以阻拦所有的请求,进行修改,或者者修改 response。

NSHipster 上说:「或者者这么说吧: NSURLProtocol 就是一个苹果允许的中间人攻击。」

能做什么?

  • 重定向网络请求(可以处理之前电信的 DNS 域名劫持问题)
  • 缓存
  • 自己设置 Response (过滤敏感信息)
  • 全局网络请求设置
  • HTTP Mocking

使用方法

1. 子类化:

因为 NSURLProtocol 是一个笼统类,所以使用的时候必需定义一个它的子类:

#import <Foundation/Foundation.h>@interface ZDYURLProtocol : NSURLProtocol@end

2. 注册:

[NSURLProtocol registerClass:[ZDYURLProtocol class]];

NSURLConnection 发起请求的时候,会让所有已注册的 URLProtocol 来“审批”这个请求

注意: 假如是基于 NSURLSession 进行的请求,注册的时候需要注册到 NSURLSessionConfiguration 中:

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];    NSArray *protocolArray = @[[ZDYURLProtocol class]];    configuration.protocolClasses = protocolArray;    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];    NSURLSessionTask *task = [session dataTaskWithRequest:request];    [task resume];

记得用完之后注销:

[NSURLProtocol unregisterClass:[MyURLProtocol class]];

3. 笼统对象必需实现的方法

注册成功之后,就需要我们的子类去实现笼统方法:

+ (BOOL)canInitWithRequest:(NSURLRequest *)request;+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request;+ (BOOL)requestIsCacheEquivalent:(NSURLRequest *)a toRequest:(NSURLRequest *)b;- (void)startLoading;- (void)stopLoading;
canInitWithRequest

用来审批的方法。

前面说到「NSURLConnection 发起请求的时候,会让所有已注册的 URLProtocol 来“审批”这个请求」。这里返回NO代表放过这个请求,不作解决。返回YES,代表需要解决,则会进入后续的流程。

注意:这里需要放过已经解决过的请求:

+ (BOOL)canInitWithRequest:(NSURLRequest *)request {        //解决过的,放过    if ([NSURLProtocol propertyForKey:URLProtocolHandledKey inRequest:request]) {        return NO;    }        // 你的逻辑代码        return NO;}
canonicalRequestForRequest

这个方法用来统一解决请求 request 对象的,可以修改头信息,或者者重定向。没有特殊需要,则直接return request;

假如要在这里做重定向以及头信息的时候注意检查能否已经增加,由于这个方法可能被调用屡次,也可以在后面的方法中做。

+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {    return request;}
requestIsCacheEquivalent

判断网络请求能否一致,一致的话使用缓存数据。没需要就调用 super 的方法。

+ (BOOL)requestIsCacheEquivalent:(NSURLRequest *)a toRequest:(NSURLRequest *)b {    return [super requestIsCacheEquivalent:a toRequest:b];}
startLoading

子类中最重要的方法就是 -startLoading 和 -stopLoading,实现请求和取消流程。不同的自己设置子类在调用这两个方法是会传入不同的内容,但共同点都是要围绕 protocol 用户端进行操作。

可以在这里修改请求信息,重定向,DNS解析,返回自己设置的测试数据。

重点:需要标记已经解决过的 request:

- (void)startLoading {    NSMutableURLRequest *mutableReqeust = [[self request] mutableCopy];    //request解决过的放进去    [NSURLProtocol setProperty:@YES forKey:URLProtocolHandledKey inRequest:mutableReqeust];    self.connection = [NSURLConnection connectionWithRequest:mutableReqeust delegate:self];}

URLProtocolHandledKey 是:

static NSString * const URLProtocolHandledKey = @"URLProtocolHandledKey";

举例:直接在 startLoading 中返回测试数据:

        NSData *data = [@"testData" dataUsingEncoding:NSUTF8StringEncoding];        NSURLResponse *response = [[NSURLResponse alloc] initWithURL:mutableReqeust.URL                                                            MIMEType:@"text/plain"                                               expectedContentLength:data.length                                                    textEncodingName:nil];        [self.client URLProtocol:self              didReceiveResponse:response              cacheStoragePolicy:NSURLCacheStorageNotAllowed];        [self.client URLProtocol:self didLoadData:data];        [self.client URLProtocolDidFinishLoading:self];
stopLoading
- (void)stopLoading {    [self.connection cancel];    self.connection = nil;}

4. 阻拦之后的解决过程

需要注意的是父类中有一个 client 属性。

/*!     @method client    @abstract Returns the NSURLProtocolClient of the receiver.     @result The NSURLProtocolClient of the receiver.  */@property (nullable, readonly, retain) id <NSURLProtocolClient> client;

实现的协议 <NSURLProtocolClient> 如下:

- (void)URLProtocol:(NSURLProtocol *)protocol wasRedirectedToRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse;- (void)URLProtocol:(NSURLProtocol *)protocol cachedResponseIsValid:(NSCachedURLResponse *)cachedResponse;- (void)URLProtocol:(NSURLProtocol *)protocol didReceiveResponse:(NSURLResponse *)response cacheStoragePolicy:(NSURLCacheStoragePolicy)policy;- (void)URLProtocol:(NSURLProtocol *)protocol didLoadData:(NSData *)data;- (void)URLProtocolDidFinishLoading:(NSURLProtocol *)protocol;- (void)URLProtocol:(NSURLProtocol *)protocol didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;- (void)URLProtocol:(NSURLProtocol *)protocol didCancelAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;

对于需要解决的 connection,可以在下的 NSURLConnectionDataDelegate 中进行操作:

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {    [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];}- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {    [self.client URLProtocol:self didLoadData:data];}- (void) connectionDidFinishLoading:(NSURLConnection *)connection {    [self.client URLProtocolDidFinishLoading:self];}- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {    [self.client URLProtocol:self didFailWithError:error];}

注意事项:

假如我们顺序注册 A B C 三个 Protocol,那么一个 connection 在发送的时候,解决的顺序是 C B A,而且最多只有一个 Protocol 会触发解决。

阻拦 UIWebview 的请求,会有被拒的风险。

注意标记解决过的,具体做法在本文搜关键词 URLProtocolHandledKey

说明
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » NSURLProtocol 使用笔记,注意事项

发表回复