Swift中URL编码空格转%20后二次转码为%2520的技术问题
解决URL参数二次编码的问题
我来帮你搞定这个参数二次编码的困扰!你遇到的核心问题是手动对参数值做了URL编码,而URLComponents本身会自动处理编码逻辑,导致重复编码——原本的%20被再次转成了%2520(因为%字符在URL里会被编码为%25)。
问题原因拆解
你当前的代码里,手动对参数值执行了addingPercentEncoding(withAllowedCharacters: .urlHostAllowed),但URLComponents在生成最终URL时,会自动对URLQueryItem的value进行标准URL编码。这就造成了两次编码:
- 你手动把空格转成了
%20 URLComponents又把%转成了%25,最终变成%2520
修复后的代码
只需要去掉手动编码的步骤,让URLComponents自动处理即可:
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)") urlComponents.queryItems?.append(queryItem) } printLog("url before query items ", urlRequest.url!) urlRequest.url = urlComponents.url } } }
为什么这样能解决问题?
URLComponents会严格按照URL规范处理URLQueryItem的value:
- 空格会被正确编码为
%20 - 其他非法字符(比如中文、特殊符号)也会被自动转成符合标准的编码格式
- 完全不需要我们手动干预,从根源上避免了重复编码的问题
修改后,生成的URL就会符合你的期望:https://xxxxxxxxx.net/api/v1/merchant/list?q=filter&showRPPS=true&industry=insurance%20sys
内容的提问来源于stack exchange,提问作者Himan Dhawan
相关产品推荐
相关产品推荐

