Hel*_*naM 6 proxy uiwebview nsurlrequest ios
我正在设置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];
Run Code Online (Sandbox Code Playgroud)
我真的很感谢你的帮助
您可以为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);
Run Code Online (Sandbox Code Playgroud)
希望这可以帮到你.
忘记将自定义NSURLProtocol注册到您的代理人.
您无法将代理添加到 NSURLRequest。您将需要使用第三方库,例如ASIHTTPRequest。
// Configure a proxy server manually
NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com/ignore"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setProxyHost:@"192.168.0.1"];
[request setProxyPort:3128];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9480 次 |
| 最近记录: |