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

标签 ios uiwebview proxy nsurlrequest

我正在设置一个 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/

相关文章:

ios - XCode 7 Swift - 调用可以抛出,它没有标记为 'try' 并且错误没有被处理

swift - UIWebView - PDF 阴影和页码

r - twitter api 的 httr::oauth1.0_token 错误

heroku - 可以在heroku上创建代理服务器吗?

c# - 如何使用 C# 测试代理?

ios - CJSONDeserializer IOS 错误

iphone - 如何在 xCode 中比较浮点十进制数范围?

ios - 如何在IOS中加载.xlsb

ios - 触摸开始功能说触摸从未使用过

javascript - 如何突出显示 UIWebView 中第一次出现的字符串?