gpt4 book ai didi

ios - Swift 在 GET 参数中编码 &

转载 作者:可可西里 更新时间:2023-11-01 00:35:47 25 4
gpt4 key购买 nike

我有一个简单的 GET 登录请求。用户名是Silver,密码是MOto&@10
我正在使用 SwiftHttp处理请求的框架。在点击登录请求时,我总是收到错误的响应。
但是,在浏览器上点击登录请求 url(用服务器替换实际域)时,我明白了:
https://server/api/check-access/by-login-pass?_key=wlyOF7TM8Y3tn19KUdlq&login=silver&pass=MOto%26@10

密码中的 & 编码有问题。尽管我已将其替换为百分比编码。这是我的代码:

do {               
let passwordString = self.convertSpecialCharacters(string: password.text!)
print("%@", passwordString)
let opt = try HTTP.GET(Constants.kLoginUrl, parameters: ["login": username.text!, "pass": passwordString])
opt.start { response in
if let err = response.error {
print("error: \(err.localizedDescription)")
return
}

print("opt finished: \(response.description)")
self.parseLoginResponse(response.data)
}
} catch _ as NSError {

}

这是convertSpecialCharacters:

func convertSpecialCharacters(string: String) -> String {
var newString = string

let arrayEncode = ["&", "<", ">", "\"", "'", "-", "..."]

for (escaped_char) in arrayEncode {
newString = newString.encode(escaped_char)
}

return newString
}

编码扩展:

extension String {
func encode(_ chars: String) -> String
{
let forbidden = CharacterSet(charactersIn: chars)
return self.addingPercentEncoding(withAllowedCharacters: forbidden.inverted) ?? self
}
}

最佳答案

一种合适的方法是使用处理所有百分比编码的 URLComponents:

var urlComponents = URLComponents(string: "https://server/api/check-access/by-login-pass")!
let queryItems = [URLQueryItem(name:"_key", value:"wlyOF7TM8Y3tn19KUdlq"),
URLQueryItem(name:"login", value:"silver"),
URLQueryItem(name:"pass", value:"MOto&@10")]
urlComponents.queryItems = queryItems
let url = urlComponents.url

print(url) // "https://server/api/check-access/by-login-pass?_key=wlyOF7TM8Y3tn19KUdlq&login=silver&pass=MOto%26@10"

PS:我完全同意luk2302的评论。

关于ios - Swift 在 GET 参数中编码 &,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43154754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com