我正在尝试在请求中实现编码,但问题是该编码无法正常工作。例如,如果我发送类似Lélèï
的邮件,我会得到类似lélèèï kÅ«n
的邮件。
服务器运行正常,因为它可以从Android应用正常运行。
AF.request("\(endpoint)/user",
method: .post,
parameters: ["name": user.name!,
"email": user.email!,
"password": user.password!,
"phone": user.phone!,
],
encoding: URLEncoding.default,
headers: [ "Content-Type": "application/x-www-form-urlencoded"])
.validate()
.responseJSON{ response in
//code
}
URLEncoding.default
URLEncoding.httpBody
URLEncoding.queryString
JSONEncoding.default
URL由属于US-ASCII字符集的有限字符组成。这些字符包括数字(0-9),字母(A-Z,a-z)和一些特殊字符(“-”,“。”,“ _”,“〜”):source。
许多欧洲语言使用的扩展拉丁字母,在允许的字符集中使用了某些字符,例如您的情况。为了能够将这些特殊字符作为URL中的参数发送,需要使用允许的字符集对其进行百分比编码]
guard let name = user.name?.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed) else { return }
guard let email = user.email?.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed) else { return }
guard let password = user.password?.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed) else { return
guard let phone = user.phone?.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed) else { return }
let parameters = ["name": name,
"email": email,
"password": password,
"phone": phone ]
AF.request("\(endpoint)/user",
method: .post,
parameters: parameters
encoding: URLEncoding.default,
headers: [ "Content-Type": "application/x-www-form-urlencoded"])
.validate()
.responseJSON{ response in
//code
}
[另外,请避免使用强制解包运算符!
。请使用guard
语句。