分享

iOS在所有请求里添加Header

 wintelsui 2023-03-02 发布于北京

服务器要求在所有请求当中添加Header进行验证,

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType方法拦截不到相关的css,js文件请求。这里要用NSURLProtocol,这是一个挺牛逼的类,它是一个抽象类,不能去实例化它,只能子类化NSURLProtocol,每次在对一个 URL 进行请求的时候 URL Loading System 都会向 已经注册的 Protocol 询问是否可以处理该请求。这里就看出他的作用来了. 比如: 拦截UIWebView的请求,忽略请求,重定向... ...

直接贴代码:

  1. #import <Foundation/Foundation.h>
  2. @interface NSURLProtocolCustom : NSURLProtocol
  3. @end
  1. #import "NSURLProtocolCustom.h"
  2. static NSString* const FilteredKey = @"FilteredKey";
  3. @interface NSURLProtocolCustom ()<NSURLSessionDataDelegate>
  4. @property (atomic, strong, readwrite) NSURLSessionDataTask *task;
  5. @property (nonatomic, strong ) NSURLSession *session;
  6. @end
  7. @implementation NSURLProtocolCustom
  8. + (BOOL)canInitWithRequest:(NSURLRequest *)request
  9. {
  10. //只处理http和https请求
  11. NSString *scheme = [[request URL] scheme];
  12. if ( ([scheme caseInsensitiveCompare:@"http"] == NSOrderedSame ||
  13. [scheme caseInsensitiveCompare:@"https"] == NSOrderedSame))
  14. {
  15. //看看是否已经处理过了,防止无限循环
  16. if ([NSURLProtocol propertyForKey:FilteredKey inRequest:request]) {
  17. return NO;
  18. }
  19. return YES;
  20. }
  21. return NO;
  22. }
  23. + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
  24. /** 可以在此处添加头等信息 */
  25. NSMutableURLRequest *mutableReqeust = [request mutableCopy];
  26. [mutableReqeust setValue:@"abc" forHTTPHeaderField:@"Authorization"];
  27. return mutableReqeust;
  28. }
  29. - (void)startLoading
  30. {
  31. NSMutableURLRequest *mutableReqeust = [[self request] mutableCopy];
  32. //打标签,防止无限循环
  33. [NSURLProtocol setProperty:@YES forKey:FilteredKey inRequest:mutableReqeust];
  34. NSURLSessionConfiguration *configure = [NSURLSessionConfiguration defaultSessionConfiguration];
  35. NSOperationQueue *queue = [[NSOperationQueue alloc] init];
  36. self.session = [NSURLSession sessionWithConfiguration:configure delegate:self delegateQueue:queue];
  37. self.task = [self.session dataTaskWithRequest:mutableReqeust];
  38. [self.task resume];
  39. }
  40. - (void)stopLoading
  41. {
  42. [self.session invalidateAndCancel];
  43. self.session = nil;
  44. }
  45. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
  46. {
  47. if (error != nil) {
  48. [self.client URLProtocol:self didFailWithError:error];
  49. }else
  50. {
  51. [self.client URLProtocolDidFinishLoading:self];
  52. }
  53. }
  54. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
  55. didReceiveResponse:(NSURLResponse *)response
  56. completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler
  57. {
  58. [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
  59. completionHandler(NSURLSessionResponseAllow);
  60. }
  61. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
  62. {
  63. [self.client URLProtocol:self didLoadData:data];
  64. }
  65. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask willCacheResponse:(NSCachedURLResponse *)proposedResponse completionHandler:(void (^)(NSCachedURLResponse * _Nullable))completionHandler
  66. {
  67. completionHandler(proposedResponse);
  68. }
  69. //TODO: 重定向
  70. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)newRequest completionHandler:(void (^)(NSURLRequest *))completionHandler
  71. {
  72. NSMutableURLRequest * redirectRequest;
  73. redirectRequest = [newRequest mutableCopy];
  74. [[self class] removePropertyForKey:FilteredKey inRequest:redirectRequest];
  75. [[self client] URLProtocol:self wasRedirectedToRequest:redirectRequest redirectResponse:response];
  76. [self.task cancel];
  77. [[self client] URLProtocol:self didFailWithError:[NSError errorWithDomain:NSCocoaErrorDomain code:NSUserCancelledError userInfo:nil]];
  78. }
  79. - (instancetype)initWithRequest:(NSURLRequest *)request cachedResponse:(NSCachedURLResponse *)cachedResponse client:(id<NSURLProtocolClient>)client
  80. {
  81. self = [super initWithRequest:request cachedResponse:cachedResponse client:client];
  82. if (self) {
  83. // Some stuff
  84. }
  85. return self;
  86. }
  87. @end

最后在用到的webview类里进行注册和注销即可

  1. - (void)viewDidLoad {
  2. [super viewDidLoad];
  3. [NSURLProtocol registerClass:[NSURLProtocolCustom class]];
  4. }
  1. -(void)viewWillDisappear:(BOOL)animated{
  2. [super viewWillDisappear:animated];
  3. [NSURLProtocol unregisterClass:[NSURLProtocolCustom class]];
  4. }

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多