这是代码
struct URLParameterEncoder: ParameterEncoderProtocol {
/// Takes dictionary parameters and encode them to make them safe to be passed as URLQueryItem in the URLRequest
func encode(urlRequest: inout URLRequest, with parameters: Parameters) throws {
guard let url = urlRequest.url else {throw ParameterEncoderError.missingURL}
//Only execute if there are parameters to encode
if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty {
urlComponents.queryItems = [URLQueryItem]()
for (key,value) in parameters {
let queryItem = URLQueryItem(name: key, value: "\(value)".addingPercentEncoding(withAllowedCharacters: .urlHostAllowed))
urlComponents.queryItems?.append(queryItem)
}
printLog("url before query items ", urlRequest.url!)
urlRequest.url = urlComponents.url
}
}
}
尽管 URLItem 给出了正确的输出。但是当它被添加到 URL 组件时,它会给出这个结果。
https://xxxxxxxxx.net/api/v1/merchant/list?q=filter&showRPPS=true&industry=insurance%2520sys
- scheme : “https”
- host : “xxxxxxxxx.net”
- path : “/api/v1/merchant/list”
▿ queryItems : 3 elements
▿ 0 : q=filter
- name : “q”
▿ value : Optional<String>
- some : “filter”
▿ 1 : showRPPS=true
- name : “showRPPS”
▿ value : Optional<String>
- some : “true”
▿ 2 : industry=insurance%20sys
- name : “industry”
▿ value : Optional<String>
- some : “insurance%20sys”
必需:https ://xxxxxxxxx.net/api/v1/merchant/list?q=filter&showRPPS=true&industry=insurance%20sys
实际:https ://xxxxxxxxx.net/api/v1/merchant/list?q=filter&showRPPS=true&industry=insurance%2520sys