看看iOS URL 加载系统以及NSURLProtocol
你可以为你的 NSURLRequest 编写一个自定义的 NSURLProtocol 类。自定义 NSURLProtocol 可以拦截您的请求并为每个请求添加代理。相关的方法是-(void)startLoading
,在这个方法中,你可以使用 Core-Function 这是 iOS 中的一个低级 api 来为每个请求添加代理:
//"request" is your NSURLRequest
NSURL *url = [request URL];
NSString *urlString = [url absoluteString];
CFStringRef urlStringRef = (CFStringRef) urlString;
CFURLRef myURL = CFURLCreateWithString(kCFAllocatorDefault, urlStringRef, NULL);
CFStringRef requestMethod = CFSTR("GET");
CFHTTPMessageRef myRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, requestMethod, myURL, kCFHTTPVersion1_1);
self.httpMessageRef = CFHTTPMessageCreateCopy(kCFAllocatorDefault, myRequest);
CFReadStreamRef myReadStream = CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, myRequest);
// You can add body, headers.... using core function api, CFNetwork.etc
// below code is to set proxy from code if needs
NSString *hostKey;
NSString *portKey;
if ([[[urlString scheme] lowercaseString] isEqualToString:@"https"]) {
hostKey = (NSString *)kCFStreamPropertyHTTPSProxyHost;
portKey = (NSString *)kCFStreamPropertyHTTPSProxyPort;
} else {
hostKey = (NSString *)kCFStreamPropertyHTTPProxyHost;
portKey = (NSString *)kCFStreamPropertyHTTPProxyPort;
}
//set http or https proxy, change "localhost" to your proxy host, change "5566" to your proxy port
NSMutableDictionary *proxyToUse = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"localhost",hostKey,[NSNumber numberWithInt:5566],portKey,nil];
CFReadStreamSetProperty(myReadStream, kCFStreamPropertyHTTPProxy, proxyToUse);
CFReadStreamOpen(myReadStream);
希望这可以帮到你。
不要忘记将您的自定义 NSURLProtocol 注册到您的委托。