使用 Alamofire 的无效证书、表单数据和 HTTP 标头数据
Posted
技术标签:
【中文标题】使用 Alamofire 的无效证书、表单数据和 HTTP 标头数据【英文标题】:Invalid Certificate, form data and HTTP Header data with Alamofire 【发布时间】:2016-02-22 14:59:53 【问题描述】:我想将 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)
为了合并上述 2 位经理,我这样做了:
let serverTrustPolicyManager:ServerTrustPolicyManager = ServerTrustPolicyManager(policies: serverTrustPolicies)
let manager = Alamofire.Manager(configuration: configuration, delegate: Alamofire.Manager.sharedInstance.session.delegate, serverTrustPolicyManager: serverTrustPolicyManager)
问题在于“代表”,我无法在此处找到合适的代表。或者如果有任何其他简单的方法请建议。 Swift 开发新手。
【问题讨论】:
【参考方案1】:这是解决这个问题的方法:
//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 对象来创建请求。
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)")
)
【讨论】:
以上是关于使用 Alamofire 的无效证书、表单数据和 HTTP 标头数据的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 Alamofire 访问具有无效证书的本地 Https?
针对多个 CA 的 Alamofire 5 自定义 SSL 验证