菜鸟教程小白 发表于 2022-12-11 16:58:50

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


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

<pre><code>NSURLRequest *request = ;
// 2

NSString* proxyHost =@&#34;xxx.xxx.xx.x.&#34;;
NSNumber* proxyPort = @&#34;Myport&#34;;

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

                            };

NSURLSessionConfiguration *configuration = ;
configuration.connectionProxyDictionary = proxyDict;
AFURLSessionManager *manager = [ initWithSessionConfiguration:configuration];
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    if (error) {
      NSLog(@&#34;Error: %@&#34;, error);
    } else {
      NSLog(@&#34;%@ %@&#34;, response, responseObject);
    }
}];
;
</code></pre>

<p>但同样没有给我任何东西,只是给出了超时错误。
所以请帮助找到相同的解决方案</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><pre><code>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 &#34;myCustomKey&#34;
    }

    // MARK: NSURLProtocol

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

      return true
    }

    override class func canonicalRequestForRequest(request: NSURLRequest) -&gt; NSURLRequest {
      return request
    }

    override func startLoading() {

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

      NSURLProtocol.setProperty(&#34;true&#34;, 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() -&gt; NSURLSessionConfiguration {
      let proxy_server: CFString = &#34;myProxyServer.com&#34; // proxy server

      let proxy_port: CFNumber = 1234 // port


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

      let proxyDict: =

      let config = NSURLSessionConfiguration.ephemeralSessionConfiguration()
      config.connectionProxyDictionary = proxyDict as

      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) -&gt; 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 &amp;&amp; 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(&#34;TimeStamp:\(timeStamp)\nURL: \(urlString)\n\nDATA:\(dataString)\n\n&#34;)
    }

}
</code></pre>

<p>用法:</p>

<pre><code>@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: &#34;http://www.google.com&#34;)
      let req = NSURLRequest(URL: url!)
      /* if this request will be handled by our special protocol... */
      //if ( ) {
      if SpecialProtocol.canInitWithRequest(req) {
            print(&#34;SpecialProtocol.canInitWithRequest(req)&#34;)
            self.sWebViewOutlet.loadRequest(req)
      }
      else {
            print(&#34;SpecialProtocol.cantInitWithRequest(req)&#34;)
      }
    }
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 如何使用 afnetworking 将代理添加到请求中,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/38343970/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/38343970/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 如何使用 afnetworking 将代理添加到请求中