Alamofire请求使用以下命令进行调用:参数,标题和正文不起作用

编程入门 行业动态 更新时间:2024-10-27 02:24:56
本文介绍了Alamofire请求使用以下命令进行调用:参数,标题和正文不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

关于以下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请求使用以下命令进行调用:参数,标题和正文不起作用

本文发布于:2023-10-29 09:34:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1539352.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不起作用   命令   参数   标题   正文

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!