无法在URL + swift中对Plus字符进行编码 [英] Couldn't encode Plus character in URL + swift
问题描述
我正在使用GET方法,我必须在URL中传递一个电子邮件地址。 API期望它被编码。我尝试使用编码选项,但'+'字符不能被编码。
i am using a GET method in which i have to pass a email address in the URL. API expects it to be encoded. I tried with the encoding options but the '+' character couldnt be encoded.
我尝试使用以下代码
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
其中'@'字符仅被编码,'+'不被编码。
Where the '@' character is only encoded and '+' is not encoded.
推荐答案
不幸的是, CharacterSet.urlHostAllowed
和 CharacterSet.urlQueryAllowed
包含
允许。由于历史原因,大多数Web服务器将 +
替换为空格(
),因此您需要转义 +
。
Unfortunately, both CharacterSet.urlHostAllowed
and CharacterSet.urlQueryAllowed
contains +
as allowed. And for historical reason, most web servers treat +
as a replacement of whitespace (), so you need to escape
+
.
为此目的,您可能需要定义自己的 CharacterSet
For such purpose, you may need to define your own 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
这篇关于无法在URL + swift中对Plus字符进行编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!