iOS任何机构都知道如何向NSURLRequest添加代理?

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)

我真的很感谢你的帮助

adm*_*vin 7

看看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);
Run Code Online (Sandbox Code Playgroud)

希望这可以帮到你.

忘记将自定义NSURLProtocol注册到您的代理人.


sav*_*ner 2

您无法将代理添加到 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)

  • ASIHTTPRequest 不再由开发人员维护。考虑使用 AFNetworking。 (2认同)
  • 如果你深入研究 ASIHTTPRequest,`setProxyHost` 和 `setProxyPort` 是如何工作的,底层代码与我上面的答案几乎相同,ASIHTTPRequest 只是包装了所有这些底层核心功能代码。如果它不再被维护,为什么你不自己写它:-)。 (2认同)