我正在设置一个 webview,但我需要使用代理加载 webview 的内容。你们知道我如何在 NSURLRequest 中实现代理吗?
例如:
NSString *location=@"http://google.com";
NSURL *url=[NSURL URLWithString:location];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
// some code to set the proxy
[self.myWebView loadRequest:request];
非常感谢你的帮助
最佳答案
看看iOS URL Loading System以及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 注册到您的委托(delegate)。
关于iOS 任何人都知道如何向 NSURLRequest 添加代理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16847858/