Swift 如何为put方法Alamofire请求设置多个编码参数
我的请求链接是:Swift 如何为put方法Alamofire请求设置多个编码参数,swift,alamofire,Swift,Alamofire,我的请求链接是:http://et.net/webservice/put/profile?api_key=[K] &m=[m]&profile={“生日”:“1994-01-01”,“性别”:“男性”,“婚姻”:“单身”} api_key和m是url值,profile是JSON let parameters: Parameters = ["api_key": apiKey, "m": mobile,
http://et.net/webservice/put/profile?api_key=[K] &m=[m]&profile={“生日”:“1994-01-01”,“性别”:“男性”,“婚姻”:“单身”}
api_key
和m
是url值,profile
是JSON
let parameters: Parameters = ["api_key": apiKey,
"m": mobile,
"profile": ["birthday":"",
"gender": "Male",
"marital": "Single"]]
如果你想在你的网址,你将不得不百分之编码他们。您可以使用
URLComponents
来执行此操作
因此,根据需要构建JSON字符串:
let dictionary = [
"birthday": "1994-01-01",
"gender": "MALE",
"marital": "SINGLE"
]
let data = try! JSONEncoder().encode(dictionary)
let jsonString = String(data: data, encoding: .utf8)!
然后,您可以构建URL并执行请求:
let urlString = "http://et.net/webservice/put/profile"
var components = URLComponents(string: urlString)!
components.queryItems = [
URLQueryItem(name: "api_key", value: "[K]"),
URLQueryItem(name: "m", value: "[M]"),
URLQueryItem(name: "profile", value: jsonString)
]
Alamofire.request(components.url!, method: .put)
.response { response in
// do whatever you want
}
如果您正在构建一个
.post
请求,您可以让Alamofire为您将其编码到请求正文中:
let parameters = [
"api_key": "[K]",
"m": "[M]",
"profile": jsonString
]
Alamofire.request(urlString, method: .post, parameters: parameters)
.response { response in
// do whatever you want
}
你试过什么?你看过这些文件了吗?使用“参数”并不意味着你是对的。Alamofire将这些放在请求主体中。您希望它出现在
.put
请求的URL中。因此,请使用URLComponents
对其进行百分比编码。见修改后的答案。请参阅我的问题我在JSON字典中有blood参数,当post(Plus+)blood不接受时