关于以下Alamofire代码,我有两个问题。
即使我在参数中有action = heartbeat,但我删除了URL末尾的?action = heartbeat,我的JSON也失败了,为什么?
如何在下面的AF.request代码中添加我的JSON数据/正文?
let urlString = intelipos.dynalias/ioc/rest.asp?action=heartbeat let参数= [ action: heartbeat] let标头:HTTPHeaders = [ Content-Type: application / json] AF.request(urlString,方法:.post,参数:参数,编码:URLEncoding.httpBody,标头:标头).responseJSON {response在转换response.result { case .success: print( Validation Success) case let .failure(error): print(error)} }解决方案
问题一
您需要编码为查询字符串
let urlString = intelipos.dynalias/ioc/rest.asp let参数= [ action:心跳] let标头:HTTPHeaders = [ Content-Type : application / json] AF.request(urlString,方法:.post,参数:参数,编码:URLEncoding.queryString,标头:标头).responseJSON {在中响应切换response.result { case .success: print( Validation Success) case let .failure(error): print(error)} }
第二个问题
您必须准备一个可编码模型并将其传递给 parameters 参数并将编码设置为 JSONEncoding.default
请参阅此文章: medium/whoknows-swift/swift-4-decodable-encodable-3085305a9618
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 = "intelipos.dynalias/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
You need to encode as a querystring
let urlString = "intelipos.dynalias/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: medium/whoknows-swift/swift-4-decodable-encodable-3085305a9618
更多推荐
Alamofire请求使用以下命令进行调用:参数,标题和正文不起作用
发布评论