Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS any body knows how to add a proxy to 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?

for example:

    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];

I'll really appreciate your help

like image 851
HelenaM Avatar asked May 31 '13 00:05

HelenaM


2 Answers

Take a look at iOS URL Loading System as well as NSURLProtocol

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);

hope this can help you.

Do forget to register your custom NSURLProtocol to your delegate.

like image 162
admar.kevin Avatar answered Sep 28 '22 00:09

admar.kevin


You cannot add a proxy to NSURLRequest. You will need to use a 3rd party library like 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];
like image 39
savner Avatar answered Sep 28 '22 00:09

savner