How to add a HTTPS proxy to NSURLSession in SWIFT

2019-03-31 10:27发布

I have used the following code for connecting to the proxy server and works great for only HTTP requests but not for HTTPS. In iOS 9.0, kCFStreamPropertyHTTPSProxyHost and kCFStreamPropertyHTTPSProxyPort are depreciated.

let myPortInt = 12345;
let myProxyUrlString = "myProxyURL";

    let sessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration();
    sessionConfiguration.connectionProxyDictionary = [
        kCFNetworkProxiesHTTPEnable: true,
        kCFNetworkProxiesHTTPPort: myPortInt,
        kCFNetworkProxiesHTTPProxy: myProxyUrlString,
    ]
    let url = NSURL(string: endPointUrl)
    let postRequest = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 10.0)


    let jsonString =  bodyString
    postRequest.HTTPBody = jsonString 
    postRequest.HTTPMethod = "POST"
    postRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")

    let session = NSURLSession(configuration: sessionConfiguration)       
    let task = session.dataTaskWithRequest(postRequest){}

1条回答
beautiful°
2楼-- · 2019-03-31 10:36

I found the solution for adding HTTPS proxy to NSURLsession

   let proxyDict : NSDictionary = ["HTTPEnable": Int(1), "HTTPProxy": myProxyUrlString, "HTTPPort": myPortInt, "HTTPSEnable": Int(1), "HTTPSProxy": myProxyUrlString, "HTTPSPort": myPortInt]

    let sessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration();
查看更多
登录 后发表回答