Alamofire请求呼叫:参数,标题和正文不起作用

时间:2019-11-14 11:01:31

标签: swift alamofire swift5

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

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

如何在下面的AF.request代码中添加我的JSON数据/正文?

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)
  }
}

2 个答案:

答案 0 :(得分:1)

  

第一个问题

您需要编码为查询字符串

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)
  }
}
  

第二个问题

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

请参阅此文章:https://medium.com/whoknows-swift/swift-4-decodable-encodable-3085305a9618

答案 1 :(得分:1)

类似的东西。

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


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