我有这个Swift代码
var request = URLRequest(url: URL(string: "http://www.centill.com/ajax/logreg.php")!)
request.httpMethod = "POST"
let postString = "app_log_pass=\(pass_text_field.text!)"
request.httpBody = postString.data(using: .utf8)
当我的文字是
(1&*^&&2
它只打印(1
。如何使用Swift安全地发送包含各种符号的字符串?
答案 0 :(得分:1)
正如Sulthan建议的那样,如果要在POST数据中包含一些符号字符,则不能将预定义CharacterSet
用于实际服务器。
我经常使用的示例CharacterSet
:
extension CharacterSet {
static let rfc3986Unreserved = CharacterSet(charactersIn:
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~")
}
let postValue = "(1&*^&&2"
let postString = "app_log_pass=\(postValue.addingPercentEncoding(withAllowedCharacters: .rfc3986Unreserved)!)"
print(postString) //->app_log_pass=%281%26%2A%5E%26%262
另一个适用于普通PHP服务器的CharacterSet
:
extension CharacterSet {
static let queryValueAllowed = CharacterSet.urlQueryAllowed.subtracting(CharacterSet(charactersIn: "&+="))
}
let postValue = "(1&*^&&2"
let postString = "app_log_pass=\(postValue.addingPercentEncoding(withAllowedCharacters: .queryValueAllowed)!)"
print(postString) //->app_log_pass=(1%26*%5E%26%262
无论如何,您需要单独转义键和值,以防止转义分隔符=
。
<强> ADDITION 强>
转义多个键值对的示例:
extension String {
var queryValueEscaped: String {
return self.addingPercentEncoding(withAllowedCharacters: .queryValueAllowed)!
}
}
let params: [String: String] = [
"app_log_usn": "OOPer",//usn_text_field.text!,
"app_log_pass": "(1&*^&&2"//pass_text_field.text!
]
let postString = params.map {"\($0.key)=\($0.value.queryValueEscaped)"}.joined(separator: "&")
print(postString) //->app_log_usn=OOPer&app_log_pass=(1%26*%5E%26%262
假设每个密钥都是由安全字符构成的,不需要逃避。
答案 1 :(得分:-1)
将addingPercentEncoding方法与urlHostsAllowed参数一起使用:
string.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)