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

依然范特西╮ 提交于 2020-01-25 06:57:27

问题


I have two questions with regards to the Alamofire code below.

My JSON fails if I remove the ?action=heartbeat at the end of the URL even though I have action = heartbeat in the parameters, why?

How do I add my JSON data/body in the AF.request code below?

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

回答1:


Question One

You need to encode as a querystring

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

You have to prepare an encodable model and pass it in parameters argument and set encoding to JSONEncoding.default

Refer this article: https://medium.com/whoknows-swift/swift-4-decodable-encodable-3085305a9618




回答2:


Something like that.

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


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


来源:https://stackoverflow.com/questions/58855248/alamofire-request-call-with-parameters-headers-and-body-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!