iOS 任何人都知道如何向 NSURLRequest 添加代理? [英] iOS any body knows how to add a proxy to NSURLRequest?

查看:25
本文介绍了iOS 任何人都知道如何向 NSURLRequest 添加代理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

非常感谢您的帮助

推荐答案

看看 iOS URL 加载系统 以及 NSURLProtocol

您可以为您的 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 添加代理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆