无法在URL + swift中对Plus字符进行编码
我正在使用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服务器将+
视为空白的替代( ),所以你需要逃避
+
。
为了达到这个目的,你可能需要定义你自己的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
当您使用.urlHostAllowed字符集“+”不编码。
像下面添加扩展到string
public func stringByAddingPercentEncodingToData() -> String? { let finalString = self.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed)?.replacingOccurrences(of: "&", with: "%26").replacingOccurrences(of: "+", with: "%2B") return finalString }
你可以做这样的事情。
尝试这个 :
let encodedEmail = emailAddressTxt.text! var urlString = "http://yyy.xxx.com/User/GetUserDetailsByEmailAddress?EmailAddress=\(encodedEmail)" urlString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
要么
让encodedEmail = emailAddressTxt.text!
let urlString = "http://yyy.xxx.com/User/GetUserDetailsByEmailAddress?EmailAddress=\(encodedEmail!)" urlString = urlString.addingPercentEncoding(withAllowedCharacters:.urlHostAllowed) print(escapedString)