这是我用来使用代理主机和端口发送请求的代码。我知道实现是正确的,因为我得到了 407 状态码(需要代理身份验证)。我不知道为什么代理服务器的用户名/密码不起作用。凭据正确且代理处于活动状态。
class Request: NSOperation, NSURLSessionDelegate {
private var URL:NSURL = NSURL()
private var method: String
private var params: String
private var session: NSURLSession = NSURLSession.sharedSession()
private var cookies: [NSHTTPCookie] = [NSHTTPCookie]()
private var httpResponse: NSHTTPURLResponse?
private var contentsOfURL: String?
private var statusCode: Int?
var isConnecting = false
var shouldUseProxy = false
var proxyHost:CFString!
var proxyPort:CFNumber!
var proxyUser:CFString!
var proxyPW:CFString!
init(URL: NSURL, method: String, params: String, cookies:[NSHTTPCookie]) {
self.URL = URL
self.params = params
self.method = method
self.cookies = cookies
}
override func main() -> () {
let request = NSMutableURLRequest(URL: self.URL)
request.HTTPMethod = self.method
if method == "POST" {
request.HTTPBody = params.dataUsingEncoding(NSUTF8StringEncoding)
}
if self.shouldUseProxy {
let proxyEnable = NSNumber(int: 1) as NSNumber
let proxyDict: [NSObject:AnyObject] = [
kCFNetworkProxiesHTTPEnable: proxyEnable,
kCFStreamPropertyHTTPProxyHost: self.proxyHost,
kCFStreamPropertyHTTPProxyPort: self.proxyPort,
kCFStreamPropertyHTTPSProxyHost: self.proxyHost,
kCFStreamPropertyHTTPSProxyPort: self.proxyPort,
kCFProxyTypeKey: kCFProxyTypeHTTPS,
kCFProxyUsernameKey: self.proxyUser,
kCFProxyPasswordKey: self.proxyPW
]
let config = NSURLSessionConfiguration.ephemeralSessionConfiguration()
config.connectionProxyDictionary = proxyDict
self.session = NSURLSession.init(configuration: config, delegate: self, delegateQueue: NSOperationQueue())
}
let task = session.dataTaskWithRequest(request) {
(data, response, error) in
if error == nil {
let httpResponse = response as! NSHTTPURLResponse
let statusCode = httpResponse.statusCode
print("statusCode \(statusCode)")
}
self.isConnecting = false
}
task.resume()
}
}