如何使用afnetworking将代理添加到请求中

时间:2016-07-13 06:19:25

标签: ios proxy afnetworking uiwebviewdelegate

我一直在尝试使用afnetworking为我的webView中打开的链接添加代理。我正在设置webview但我需要使用代理加载webview的内容。你们中的任何人都知道如何在NSURLRequest中实现代理?我做的是这个:

NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 2

NSString* proxyHost =  @"xxx.xxx.xx.x.";
NSNumber* proxyPort = @"Myport";

// Create an NSURLSessionConfiguration that uses the proxy
NSDictionary *proxyDict = @{
                            (NSString *)( kCFNetworkProxiesHTTPEnable):[NSNumber numberWithInt:1],
                            (NSString *)(kCFNetworkProxiesHTTPProxy):proxyHost,
                            (NSString *)(kCFNetworkProxiesHTTPPort):proxyPort

                            };

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
configuration.connectionProxyDictionary = proxyDict;
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    if (error) {
        NSLog(@"Error: %@", error);
    } else {
        NSLog(@"%@ %@", response, responseObject);
    }
}];
[dataTask resume];

但同样不给我任何东西,只是给出超时错误。 所以请帮助找到相同的解决方案

1 个答案:

答案 0 :(得分:0)

import UIKit
import CoreFoundation

class SpecialProtocol: NSURLProtocol, NSURLSessionDataDelegate, NSURLSessionTaskDelegate {
//var httpMessageRef: CFHTTPMessage;()
    var httpMessageRef: CFHTTPMessage?

    class func registerSpecialProtocol() {
        var inited: Bool = false
        if !inited {
            NSURLProtocol.registerClass(SpecialProtocol.self)
            inited = true
        }
    }


    private var dataTask:NSURLSessionDataTask?
    private var urlResponse:NSURLResponse?
    private var receivedData:NSMutableData?

    class var CustomKey:String {
        return "myCustomKey"
    }

    // MARK: NSURLProtocol

    override class func canInitWithRequest(request: NSURLRequest) -> Bool {
        if (NSURLProtocol.propertyForKey(SpecialProtocol.CustomKey, inRequest: request) != nil) {
            return false
        }

        return true
    }

    override class func canonicalRequestForRequest(request: NSURLRequest) -> NSURLRequest {
        return request
    }

    override func startLoading() {

        let newRequest = self.request.mutableCopy() as! NSMutableURLRequest

        NSURLProtocol.setProperty("true", forKey: SpecialProtocol.CustomKey, inRequest: newRequest)

        let defaultConfigObj = customizeEphemeralSessionConfiguration()//NSURLSessionConfiguration.defaultSessionConfiguration()
        let defaultSession = NSURLSession(configuration: defaultConfigObj, delegate: self, delegateQueue: nil)

        self.dataTask = defaultSession.dataTaskWithRequest(newRequest)
        self.dataTask!.resume()

    }

    func customizeEphemeralSessionConfiguration() -> NSURLSessionConfiguration {
        let proxy_server: CFString = "myProxyServer.com" // proxy server

        let proxy_port: CFNumber = 1234 // port


        let hostKey: NSString = kCFNetworkProxiesHTTPProxy as NSString
        let portKey: NSString = kCFNetworkProxiesHTTPPort as NSString

        let proxyDict:[String:AnyObject] = [kCFNetworkProxiesHTTPEnable as String: true, hostKey as String:proxy_server, portKey as String: proxy_port]

        let config = NSURLSessionConfiguration.ephemeralSessionConfiguration()
        config.connectionProxyDictionary = proxyDict as [NSObject : AnyObject]

        return config
    }


    override func stopLoading() {
        self.dataTask?.cancel()
        self.dataTask       = nil
        self.receivedData   = nil
        self.urlResponse    = nil
    }

    // MARK: NSURLSessionDataDelegate

    func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask,
                    didReceiveResponse response: NSURLResponse,
                                       completionHandler: (NSURLSessionResponseDisposition) -> Void) {

        self.client?.URLProtocol(self, didReceiveResponse: response, cacheStoragePolicy: .NotAllowed)

        self.urlResponse = response
        self.receivedData = NSMutableData()

        completionHandler(.Allow)
    }

    func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
        self.client?.URLProtocol(self, didLoadData: data)

        self.receivedData?.appendData(data)
    }

    // MARK: NSURLSessionTaskDelegate

    func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
        if error != nil && error!.code != NSURLErrorCancelled {
            self.client?.URLProtocol(self, didFailWithError: error!)
        } else {
            saveCachedResponse()
            self.client?.URLProtocolDidFinishLoading(self)
        }
    }

    // MARK: Private methods

    /**
     Do whatever with the data here
     */
    func saveCachedResponse () {
        let timeStamp = NSDate()
        let urlString = self.request.URL?.absoluteString
        let dataString = NSString(data: self.receivedData!, encoding: NSUTF8StringEncoding) as NSString?
        print("TimeStamp:\(timeStamp)\nURL: \(urlString)\n\nDATA:\(dataString)\n\n")
    }

}

用法:

@IBOutlet weak var sWebViewOutlet : UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        setupViewDidLoad()
    }

    func setupViewDidLoad() {
        SpecialProtocol.registerSpecialProtocol()

        let url = NSURL(string: "http://www.google.com")
        let req = NSURLRequest(URL: url!)
        /* if this request will be handled by our special protocol... */
        //if ( [SpecialProtocol canInitWithRequest:request] ) {
        if SpecialProtocol.canInitWithRequest(req) {
            print("SpecialProtocol.canInitWithRequest(req)")
            self.sWebViewOutlet.loadRequest(req)
        }
        else {
            print("SpecialProtocol.cantInitWithRequest(req)")
        }
    }