• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

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

[复制链接]
菜鸟教程小白 发表于 2022-12-11 16:58:50 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我一直在尝试为要使用 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];

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



Best Answer-推荐答案


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)")
        }
    }

关于ios - 如何使用 afnetworking 将代理添加到请求中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38343970/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap