gpt4 book ai didi

ios - URL 中编码 "&"的问题

转载 作者:搜寻专家 更新时间:2023-10-31 22:32:27 24 4
gpt4 key购买 nike

我必须向使用 Swift 1.2 开发的 iPhone 应用程序中的 Web 服务发送 https GET 请求。

我正在尝试构造查询字符串参数,但在发送到服务器之前必须对其进行编码。

一切正常,但当密码包含“&”字符时无法正常工作。期望将“&”字符编码为“%26”但不工作...

刚刚在有'%'时做了一个测试。与提供“%25”的“%”一起按预期工作。但不要转换 '&' 符号....

尝试了以下方法:

var testPassword1: String = "mypassword&1"

var testPassword2: String = "mypassword%1"


// Try to encode 'testPassword1'
testPassword1.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
testPassword1.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!


// Try to encode 'testPassword2'
testPassword2.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
testPassword2.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!

我已经完成了上述测试,以下是响应

enter image description here

想知道正确的方法来做到这一点。谢谢。

最佳答案

你应该使用 NSURLComponents为你的任务。

给定一个 URL 字符串,创建一个 url-components:

let urlString = "http://example.com"
let urlComponents = NSURLComponents(string: urlString)!

给定一个查询参数容器(可能是一个字典,或者一个(字符串,字符串?)元组数组),创建一个 NSURLQueryItems 数组:

let queryParameters: [String: String?] = ["param": "az09-._~!$&'()*+,;=:@/?", "reserved": ":/?#[]@!$&'()*+,;="]
var queryItems = queryParameters.map { NSURLQueryItem(name: $0.0, value: $0.1) }

将查询组件附加到 url 组件:

urlComponents.queryItems = queryItems.count > 0 ? queryItems : nil

print(urlComponents.string!)

打印:

http://example.com?reserved=:/?%23%5B%5D@!$%26'()*+,;%3D&param=az09-._~!$%26'()*+,;%3D:@/?

关于ios - URL 中编码 "&"的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36773822/

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