swift 使用Alamofire访问Localhost API

ffx8fchx  于 2023-08-02  发布在  Swift
关注(0)|答案(1)|浏览(121)

我的网址https://localhost:44301/api/authenticate swift 5 Alamofire 5+
以上本地主机是我的 Swagger 和 Postman 与SSL禁用工作,我得到适当的回应

private let session: Session = {
    let manager = ServerTrustManager(evaluators: ["localhost:44301": DisabledTrustEvaluator()])
    let configuration = URLSessionConfiguration.af.default

    return Session(configuration: configuration, serverTrustManager: manager)
}()

//POST method call using Alamofire
let strURL = https://localhost:44301/api/authenticate
session.request(strURL, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON {
...
//handle response
}

字符串
我得到的错误

Url : https://localhost:44301/api/Authenticate, Parameters : {"userNameOrEmailAddress":"admin","password":"123qwe"}
failure(Alamofire.AFError.serverTrustEvaluationFailed(reason: Alamofire.AFError.ServerTrustFailureReason.noRequiredEvaluator(host: "localhost")))
serverTrustEvaluationFailed(reason: Alamofire.AFError.ServerTrustFailureReason.noRequiredEvaluator(host: "localhost"))


我已经在ServerTrustManager中尝试了localhost而不是localhost:44301,仍然错误

z0qdvdin

z0qdvdin1#

您需要创建自定义会话

private let session: Session = {
    // Create the server trust manager
    let serverTrustManager = ServerTrustManager(evaluators: ["localhost": DisabledTrustEvaluator()])
    
    // Create custom session
    let configuration = URLSessionConfiguration.default
    configuration.headers = .default
    let man = Session(
        configuration: URLSessionConfiguration.default,
        serverTrustManager: serverTrustManager
    )
    return man
}()

字符串
之后

session.request(url).response { response in
    switch response.result {
    case let .success(data):
        debugPrint("data = \(data)")
    case let .failure(error):
        debugPrint("error = \(error)")
    }
}

相关问题