我正在使用GET方法,我必须在URL中传递电子邮件地址.API期望它被编码.我试过编码选项,但'+'字符无法编码.
我尝试使用以下代码
let encodedEmail = emailAddressTxt.text!.addingPercentEncoding(withAllowedCharacters:.urlHostAllowed) let urlString = "http://www.example.com/User/GetUserDetailsByEmailAddress?EmailAddress=\(encodedEmail!)" print(escapedString)
它打印http://www.example.com/User/GetUserDetailsByEmailAddress?EmailAddress=mano+1%40gmail.com
其中'@'字符仅被编码而'+'未被编码.
不幸的是,CharacterSet.urlHostAllowed
和CharacterSet.urlQueryAllowed
包含+
的允许.由于历史原因,大多数Web服务器都将其+
视为whitespace(), so you need to escape
+
.
为此,您可能需要定义自己的CharacterSet
:
extension CharacterSet { static let rfc3986Unreserved = CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~") } let emailAddressText = "mano+1@gmail.com" let encodedEmail = emailAddressText.addingPercentEncoding(withAllowedCharacters:.rfc3986Unreserved) print(encodedEmail!) //->mano%2B1%40gmail.com