问题描述
我正在设置webview,但我需要使用代理加载webview的内容。你们中的任何人都知道如何在NSURLRequest中实现代理?
I'm setting up a webview but I need to load the content of the webview using a proxy. Any of you knows how can I'm implement the proxy in 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];
我真的很感谢你的帮助
推荐答案
看看以及
您可以为NSURLRequest编写自定义NSURLProtocol类。自定义NSURLProtocol可以拦截您的请求并为每个请求添加代理。相关方法是 - (void)startLoading
,在这个方法中你可以使用Core-Function,这是iOS中的一个小级别的api,可以为每个请求添加代理:
You can write a custom NSURLProtocol class for your NSURLRequest. A custom NSURLProtocol can intercept your requests and add proxy to each request. the relevant method is -(void)startLoading
, inside this method you can use Core-Function which is a little low-level api in iOS to add the proxy to each request:
//"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。
Do forget to register your custom NSURLProtocol to your delegate.
这篇关于iOS任何机构都知道如何向NSURLRequest添加代理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!