Alamofire 返回一个无效的 URL
我正在使用以下代码形成用于搜索 (urlStrForCustSearch
) 的 URL 字符串
和URL_CUSTOMER_SEARCH = "http://pos1domain.mobi/pos/SV_IOS.asmx/IosJasonToDatatbl"
:
let customerJson = [[
"customer_id":nil,
"tel":1234567,
"email":nil,
"addr":nil,
"history":nil]]
do{
let JSONData = try JSONSerialization.data(withJSONObject: customerJson, options: [])
let JSONText = String(data: JSONData,
encoding: .utf8)!
let urlStrForCustSearch = URL_CUSTOMER_SEARCH+"?jsonText=\(JSONText)&funname=GET_MM_CUSTOMER_DTL_LST"
print(urlStrForCustSearch)
Alamofire.request(urlStrForCustSearch, method: .post, parameters: [:], encoding: URLEncoding.default, headers: [:]).responseString { response in
if response.result.isSuccess {
print("Response is success")
}else{
print("Response Failed")
print("Reason : \(response)")
}
}
}catch{
print("Cannot parse the dictionary")
}
控制台打印所需的 url
正确的网址:
http://pos1domain.mobi/pos/SV_IOS.asmx/IosJasonToDatatbl?jsonText=[{"tel":1234567,"email":null,"history":null,"customer_id":null,"addr":null}]&funname=GET_MM_CUSTOMER_DTL_LST
但是在将 urlStrForCustSearch
字符串作为参数传递给 Alamofire 时,Alamofire 返回无效的 URL
Response Failed
Reason : FAILURE: invalidURL("http://pos1domain.mobi/pos/SV_IOS.asmx/IosJasonToDatatbl?jsonText=[{\"tel\":1234567,\"email\":null,\"history\":null,\"customer_id\":null,\"addr\":null}]&funname=GET_MM_CUSTOMER_DTL_LST")
我们可以看到在url字符串中添加了'\'
任何人都可以帮助我创建不带 '\' 字符串的 url 字符串
如果需要任何输入,请告诉我。
最佳答案
反斜杠用于转义字符串中的特殊字符。
如果你想像这样尝试在 Swift 中分配一个包含双引号的字符串变量:
let str = "They said "hi" when I walked in"
Xcode 会在此处显示错误,因为您的字符串实际上以“They said”结尾(左双引号和右双引号。
为了解决这个问题,你需要转义应该是字符串一部分的双引号,就像这样
let str = "They said \"hi\" when I walked in"
如果没有这个,你在 iOS 项目中的代码就会有问题,你的 API 也会有读取字符串的问题,它就不会有效。
在 URL 中使用特殊字符时,您可以使用百分比编码对字符串进行编码,将特殊字符替换为浏览器可以理解的格式。如果您使用百分比编码转换完整的 url,它不是很可读:
http%3A%2F%2Fpos1domain%2Emobi%2Fpos%2FSV%5FIOS%2Easmx%2FIosJasonToDatatbl%3FjsonText%3D%5B%7B%22tel%22%3A1234567%2C%22email%22%3Anull%2C%22history%22%3Anull%2C%22customer%5Fid%22%3Anull%2C%22addr%22%3Anull%7D%5D%26funname%3DGET%5FMM%5FCUSTOMER%5FDTL%5FLST
因此通常最好只对 URL 的查询字符串(GET 参数)进行编码。
let baseUrlString = "http://pos1domain.mobi/pos/SV_IOS.asmx/IosJasonToDatatbl"
let queryString = "?jsonText=[{\"tel\":1234567,\"email\":null,\"history\":null,\"customer_id\":null,\"addr\":null}]&funname=GET_MM_CUSTOMER_DTL_LST".addingPercentEncoding(withAllowedCharacters: .alphanumerics)!
let urlString = baseUrlString + queryString
print(urlString)
更新 - 更好的解决方案
我完全忘记了您使用的是 Alamofire,我正在解决您提到的字符串问题。 Alamofire 可以通过将参数传递到请求调用中来自动为您处理编码。
let parameters: Parameters = ["foo": "bar"]
// All three of these calls are equivalent
Alamofire.request("https://httpbin.org/get", parameters: parameters) // encoding defaults to `URLEncoding.default`
Alamofire.request("https://httpbin.org/get", parameters: parameters, encoding: URLEncoding.default)
关于json - 从 json 字符串构建 url 时,Alamofire 返回无效的 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48684350/