我正尝试使用Alamofire发送带有正文的POST HTTP请求,希望能有所帮助。
我的身体:
{"data":{"gym":{"country":"USA","city":"San Diego","id":1}}}
我应该做这样的事情吗?
let parameters: [String: Any] = [ "data": [
"gym": [
"country":"USA",
"city":"San Diego",
"id":1
]]]
Alamofire.request(URL, method: .post, parameters: parameters, headers: headers())
.responseJSON { response in
print(response)
}
答案 0 :(得分:1)
如果您希望以json格式发送参数,请使用encoding作为JSONEncoding。因此,在请求中添加用于编码的参数,如下所示:
Alamofire.request(URL, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers())
.responseJSON { response in
print(response)
}
希望有帮助...
答案 1 :(得分:0)
尝试使用此方法将json字符串转换为字典
func convertToDictionary(text: String) -> [String: Any]? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
let str = "{\"data\":{\"gym\":{\"country\":\"USA\",\"city\":\"San Diego\",\"id\":1}}}"
let dict = convertToDictionary(text: str)
并在您的请求中将字典作为参数发送。
Alamofire.request(URL, method: .post, parameters: dict, headers: headers())
.responseJSON { response in
print(response)
}
答案 2 :(得分:0)
我认为您应该尝试使用以下格式准备字典:
var gym = [String:Any]()
gym["country"] = "USA"
gym["city"] = "San"
var data = [[String:Any]]()
data.append(gym)
var metaData = [String:Any]()
metaData["data"] = data
答案 3 :(得分:0)
您的parameters
是错误的...
let parameters: [String: Any] = { "data":
{
"gym": {
"country":"USA",
"city":"San Diego",
"id":1
}
}
}
Alamofire.request(<YOUR-URL>,
method: .post,
parameters: parameters,
encoding: URLEncoding(destination: .queryString),
headers: <YOUR-HEADER>
).validate().responseString { response in
switch response.result {
case .success:
debugPrint("Good to go.")
debugPrint(response)
case .failure:
let errMsg = String(data: response.data!, encoding: String.Encoding.utf8)!
debugPrint(errMsg)
debugPrint(response)
}
}
希望此帮助。顺便说一句,在Alamofire 5中,debugPrint(response)
可以打印出response.data directly
。