Alamofire 请求调用:参数,Headers 和 Body 不工作

Alamofire Request call with: Parameters, Headers and Body not working

关于下面的 Alamofire 代码,我有两个问题。

如果我删除了 URL 末尾的 ?action=heartbeat,我的 JSON 会失败,即使我在参数中有 action = heartbeat,为什么?

如何在下面的 AF.request 代码中添加我的 JSON data/body?

let urlString   = "https://intelipos.dynalias.net/ioc/rest.asp?action=heartbeat"
let parameters  = ["action":"heartbeat"]
let headers: HTTPHeaders = ["Content-Type":"application/json"]

AF.request(urlString, method: .post, parameters: parameters, encoding:  URLEncoding.httpBody, headers: headers).responseJSON { response in
  switch response.result {
  case .success:
    print("Validation Successful")
  case let .failure(error):
    print(error)
  }
}

Question One

您需要编码为查询字符串

let urlString   = "https://intelipos.dynalias.net/ioc/rest.asp"
let parameters  = ["action":"heartbeat"]
let headers: HTTPHeaders = ["Content-Type":"application/json"]

AF.request(urlString, method: .post, parameters: parameters, encoding:  URLEncoding.queryString, headers: headers).responseJSON { response in
  switch response.result {
  case .success:
    print("Validation Successful")
  case let .failure(error):
    print(error)
  }
}

Question Two

您必须准备一个可编码模型并将其传递到 parameters 参数中并将编码设置为 JSONEncoding.default

参考这篇文章:https://medium.com/whoknows-swift/swift-4-decodable-encodable-3085305a9618

类似的东西。

let parameters: [String: Any] = [
            "request_token" : LoginVC.REQUEST_TOKEN
        ]


        Alamofire.request("https://api.com"
, method: .post, parameters: parameters, encoding: JSONEncoding.default , headers: nil)