将字符串作为参数拼接在URL后的时候,+号在iOS端未被编码,导致服务接收到参数时解码,将+号解码为空格,未能正确获取数据。
解决办法:将特殊字符串(比如+、=号等等)手动编码
// 原url
let srcUrl = "https://www.example.com/index.html"
// 要拼接的参数(dictionary转json字符串)
let paramValue = "RScq3bv+xwg=="
// 1、先处理要拼接的参数
let allowedCharacters = CharacterSet.urlQueryAllowed.subtracting(.init(charactersIn: "+&="))
let handledValue = paramValue.addingPercentEncoding(withAllowedCharacters: allowedCharacters)
// 2、把处理好的参数拼接到URL上
var components = URLComponents(string: srcUrl)
var queryItems = components?.queryItems ?? []
let tmpQuery = URLQueryItem(name: "encryptInfo", value: handledValue)
queryItems.append(tmpQuery)
components.queryItems = queryItems
// 最终的url
let finalUrl = components.url
注意,要先处理要拼接参数字符串,再用处理好的字符串去拼接url。而不是先拼接好url,再去处理url字符串。不然会打不开页面