iOS网络请求 添加全局代理 NSURLSessionConfiguration 解决方案
1、最近做项目、文件存储服务器是用的亚马逊的、如果直接访问、下载其资源速度很慢、所以需要在网络请求的时候添加一个代理、加速网络访问
2、代理服务器是一个HTTPS 的一个服务器
3、思路、解决方案、利用运行时机制(添加分类NSURLSession+Change)针对 NSURLSession 初始化添加代理对所有的网络请求进行拦截处理
#import "NSURLSession+Change.h" @implementation NSURLSession (Change) +(void)load{ Method oldMethod = class_getClassMethod(self, @selector(sessionWithConfiguration:delegate:delegateQueue:)); Method newMethod = class_getClassMethod(self, @selector(newSessionWithConfiguration:delegate:NSURLSessiondelegateQueue:)); Method oldMethod1 = class_getClassMethod(self, @selector(sessionWithConfiguration:)); Method newMethod1 = class_getClassMethod(self, @selector(newSessionWithConfiguration:)); method_exchangeImplementations(oldMethod1, newMethod1); method_exchangeImplementations(oldMethod, newMethod); } + (NSURLSession *)newSessionWithConfiguration:(NSURLSessionConfiguration *)configuration{ configuration=[self newConfiguration:configuration]; NSURLSession *section= [self newSessionWithConfiguration:configuration]; return section; } + (NSURLSession *)newSessionWithConfiguration:(NSURLSessionConfiguration *)configuration delegate:(nullable id <NSURLSessionDelegate>)delegate NSURLSessiondelegateQueue:(nullable NSOperationQueue *)queue{ configuration=[self newConfiguration:configuration]; NSURLSession *section= [self newSessionWithConfiguration:configuration delegate:delegate NSURLSessiondelegateQueue:queue]; return section; } #pragma mark 添加代理,加速网络请求 +(NSURLSessionConfiguration *)newConfiguration:(NSURLSessionConfiguration *)configuration{ //通过服务器配置HTTPS代理 NSString *proxy=@""; NSInteger port=; configuration.connectionProxyDictionary = @{ @"HTTPEnable":@YES, @"HTTPProxy":proxy, @"HTTPPort":@(port), @"HTTPSEnable":@YES, @"HTTPSProxy":proxy, @"HTTPSPort":@(port), }; NSString *user=@""; NSString *password=@""; NSString* proxyIDPasswd = [NSString stringWithFormat:@"%@:%@",user,password]; NSData* proxyoriginData = [proxyIDPasswd dataUsingEncoding:NSUTF8StringEncoding]; NSString *base64EncodedCredential = [proxyoriginData base64EncodedStringWithOptions:0]; NSString *authString = [NSString stringWithFormat:@"Basic: %@", base64EncodedCredential]; configuration.HTTPAdditionalHeaders = @{@"Proxy-Authorization": authString}; return configuration; } @end
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构