Alamofire请求使用以下命令进行调用:参数,标题和正文不起作用 [英] Alamofire Request call with: Parameters, Headers and Body not working

查看:104
本文介绍了Alamofire请求使用以下命令进行调用:参数,标题和正文不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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



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

  let urlString = https://intelipos.dynalias.net/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)
}
}


解决方案


问题一


您需要编码为查询字符串



< pre class = lang-swift prettyprint-override> let urlString = https://intelipos.dynalias.net/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



请参阅此文章: https://medium.com/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   = "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)
  }
}

解决方案

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

这篇关于Alamofire请求使用以下命令进行调用:参数,标题和正文不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆