第1年5月6日 iOS 拦截网络请求后进行网址或ip替换

1.

#import "ReplaceURLProtocol.h"
// 为了避免canInitWithRequest和canonicalRequestForRequest的死循环
static NSString *const URLProtocolHandledKey = @"URLProtocolHandledKey";
 
// 老url网址
static NSString *const  old_url = @"baidu.com";
// 新url网址
static NSString *const  new_url = @"google.com";
@interface ReplaceURLProtocol()<NSURLSessionDelegate>
@property(nonatomic,strong)NSURLSession * session;
@end
 
@implementation ReplaceURLProtocol
+(BOOL)canInitWithRequest:(NSURLRequest *)request
{
  return YES;
}
//改变请求request
+(NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request
{
 // 业务逻辑写这里
  return request;
}
 
//开始请求
-(void)startLoading
{
 //业务逻辑写这里
}
 
//停止请求
-(void)stopLoading
{
}
 
#pragma mark ---- NSURLSessionDelegate
/*
  NSURLSessionDelegate接到数据后,通过URLProtocol传出去
 */
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
  if (error)
  {
    [self.client URLProtocol:self didFailWithError:error];
  }
  else
  {
    [self.client URLProtocolDidFinishLoading:self];
  }
}
 
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
  
  [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
  completionHandler(NSURLSessionResponseAllow);
  
}
 
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
  [self.client URLProtocol:self didLoadData:data];
}
 
@end

 

https://blog.csdn.net/zhangzeshuai/article/details/106934481

posted @ 2021-05-06 08:42  lianhuaren  阅读(218)  评论(0编辑  收藏  举报