前言
近期在一个项目中调用服务器接口需要以post
方式发送x-www-form-urlencoded
类型数据,发现使用Alamofire
死活没有把参数传给后台的问题。期间各种百度,谷歌,查Alamofire源码,最后还是在看到AFNetworking
同样问题其他同学的解决方案才摸索到的解决方案。这里确实倒腾了不少时间才解决,遂、记录一下。
AFNetworking相同问题参考:
https://www.jianshu.com/p/bf4ddd9b3663
https://blog.csdn.net/sevenquan/article/details/50537314
常规请求
func testAlamofire(_ account:String, _ pwd:String){
let urlString = "http://"
let url = NSURL(string:urlString)
var request : URLRequest = URLRequest(url: url! as URL)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let params = "{\"data\":{\"cmd\":\"Login\",\"mid\":\"H0001\",\"Data\":{\"Logid\":\"\(account)\",\"Logpass\":\"\(pwd)\",\"TypeNo\":\"O\",\"machine\":\"\(kUIID ?? "unknow")\"} }}"
let data = params.data(using: String.Encoding.utf8)
request.httpBody = data
Alamofire.request(request).responseJSON { (response) in
switch response.result.isSuccess {
case true:
let jsonData = response.data!
let jsonString = String.init(data: jsonData, encoding: .utf8)
print("response:" + jsonString!)
break
case false:
let jsonData = response.data!
let jsonString = String.init(data: jsonData, encoding: .utf8)
print("response err:" + jsonString!)
break
}
}
}
当我构建完请求认为没啥问题后一测,只见控制台
response err:缺少参数: data。
Postman测试
Postman请求如图Postman请求正常,于是各种测试传参,网上有说是编码格式,基本都试了一遍也没有效果。最后发现还是传参格式问题。具体后台接收x-www-form-urlencoded类型参数怎样的原理也没去深究,了解这方面知识的同学还望不吝赐教。
正确姿势
func testAlamofire2(_ account:String, _ pwd:String){
let urlString = "http://"
let url = NSURL(string:urlString)
var request : URLRequest = URLRequest(url: url! as URL)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let params = "data={\"cmd\":\"Login\",\"mid\":\"H0001\",\"Data\":{\"Logid\":\"\(account)\",\"Logpass\":\"\(pwd)\",\"TypeNo\":\"O\",\"machine\":\"\(kUIID ?? "unknow")\"} }"
let data = params.data(using: String.Encoding.utf8)
request.httpBody = data
Alamofire.request(request).responseJSON { (response) in
switch response.result.isSuccess {
case true:
let jsonData = response.data!
let jsonString = String.init(data: jsonData, encoding: .utf8)
print("response:" + jsonString!)
break
case false:
let jsonData = response.data!
let jsonString = String.init(data: jsonData, encoding: .utf8)
print("response err:" + jsonString!)
break
}
}
}
response:{"success":true,"msg":"登录成功","data":[{"s_work_no":"F001","vc_name":"房姐001","s_gade":"","TypeNo":"C","sex":"女"}]}
网友评论