问题
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