如何从iOS中的PAC文件获取代理信息

时间:2013-07-13 07:21:41

标签: iphone ios cocoa-touch networking proxy

我在我的应用程序中使用代理支持,这对于输入到wifi设置面板中的手动代理工作正常,但是当我们在HTTP代理部分的“自动”选项中放入自动代理pac文件时,不支持无线连接。

这些信息不包含在PAC文件中,因此是动态的,那么如何让我的iOS应用程序使用pac文件获取代理信息呢?

1 个答案:

答案 0 :(得分:0)

如果您使用的是Objective C,则可以参考以下代码段获取代理详细信息(使用 kCFNetworkProxiesProxyAutoConfigURLString ):

 CFDictionaryRef dicRef = CFNetworkCopySystemProxySettings();
//Manual Proxy Details
const NSString* proxyStr = (const NSString*)CFDictionaryGetValue(dicRef, (const void*)kCFNetworkProxiesHTTPProxy);

//Auto Config Proxy Details
NSString* proxyStr2 = ( NSString*)CFDictionaryGetValue(dicRef, (const void*)kCFNetworkProxiesProxyAutoConfigURLString);
// Return something similar to http://someIPAddress:someport/pacfile

if (proxyStr2 != nil)
{
    NSLog(@"Proxy %@", proxyStr2);
    // Create an url with the proxy pac
    NSURL *url = [NSURL URLWithString:proxyStr2];
    if (url != nil)
    {
        NSString* urlPath = [url path];
        // Url path: /pacfile
        NSLog(@"Url %@", urlPath);
        NSError* error;

        // Go fetch the content the url (PAC Content)
        NSString *content = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:&error];

        if (content == nil)
        {
            NSLog(@"StringWithContentsOfUrl Error: %@", error);
        }

        if (content != nil)
        {
            NSLog(@"PAC content: %@", content);

            // Parsing of the pac file. This is just a sample parsing script and may change based on what your PAC returns
            NSUInteger firstMatch = [content rangeOfString:@"PROXY "].location + 6;
            NSUInteger secondMatch = [content rangeOfString:@"\"" options:0 range:NSMakeRange(firstMatch , [content length] - firstMatch)].location;

            if (firstMatch < 10000 && secondMatch < 10000 && firstMatch > 0 && secondMatch > 0)
            {
               //Just a random label
                self.randLabel3.text=[NSString stringWithFormat: @"First match and second match: %tu %tu", firstMatch, secondMatch];

            }
        }
    }
}
相关问题