我想将Alamofire用于网络请求。服务器具有无效的证书,我有标头值和表单数据要发送。现在我已经尝试了许多SO问题,但到目前为止还没有运气。我得到的只是我需要正确设置Manager对象。 所以我允许无效证书:
let serverTrustPolicies: [String: ServerTrustPolicy] = ["abc.com:8080/services/v2/xyz": .DisableEvaluation]
let manager = Manager(serverTrustPolicyManager:ServerTrustPolicyManager(policies: serverTrustPolicies))
然后使用标题我做了这个:
var defaultHeaders = Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders ?? [:]
defaultHeaders["X-Auth-Module"] = "true"
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = defaultHeaders
let manager = Alamofire.Manager(configuration: configuration)
要合并上述两位经理,我这样做了:
let serverTrustPolicyManager:ServerTrustPolicyManager = ServerTrustPolicyManager(policies: serverTrustPolicies)
let manager = Alamofire.Manager(configuration: configuration, delegate: Alamofire.Manager.sharedInstance.session.delegate, serverTrustPolicyManager: serverTrustPolicyManager)
问题出在' delegate',我无法在这里找到合适的代表。或者,如果还有其他简单方法,请建议。新手Swift开发。
答案 0 :(得分:0)
以下是此问题的解决方案:
//set default headers
var defaultHeaders = Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders ?? [:]
//I required this key
defaultHeaders["X-Auth-Module"] = "1"
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = defaultHeaders
let serverTrustPolicies: [String: ServerTrustPolicy] = [
"10.10.10.1:8080": .DisableEvaluation
]
manager = Alamofire.Manager(
configuration: configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies))
// Handling challange
manager!.delegate.sessionDidReceiveChallenge = { session, challenge in
var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
var credential: NSURLCredential?
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
disposition = NSURLSessionAuthChallengeDisposition.UseCredential
credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!)
} else {
if challenge.previousFailureCount > 0 {
disposition = .CancelAuthenticationChallenge
} else {
credential = self.manager!.session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace)
if credential != nil {
disposition = .UseCredential
}
}
}
return (disposition, credential)
}
管理员准备就绪后,只需使用经理对象创建请求即可。
manager!.request(.POST, (req?.url())!, parameters: req?.headerParams(), encoding: .URL, headers:nil)
.response(completionHandler: { req, res, data, error in
print("req:\(req), res:\(res),data:\(data),error:\(error)")
})