iOS UrlSession.shared.dataTask 删除 utf-8“+”字符并替换为“”

2023-12-19

我正在使用 x-www-form-endoded 数据创建对 API 的登录调用。我在 Postman 中创建了一个 POST 并收到了 200 回复。我使用Postman的导出功能生成Android的OKHTTP代码和iOS的NSURL代码。 Android 代码工作正常,但 iOS 代码收到 401 响应。我使用 Charles Web 调试代理来查看实际为有效负载发送的内容。对于 Android,用户名正确表示为“[电子邮件受保护] /cdn-cgi/l/email-protection” 但在 iOS 中它显示为“用户名=james[电子邮件受保护] /cdn-cgi/l/email-protection“。我的iOS代码如下:

let headers = [
  "accept": "application/json",
  "cache-control": "no-cache",
  "content-type": "application/x-www-form-urlencoded"
]

let postData = NSMutableData(data: "[email protected] /cdn-cgi/l/email-protection".data(using: .utf8)!)
postData.append("&password=redacted".data(using: .utf8)!)
postData.append("&grant_type=password".data(using: .utf8)!)
postData.append("&client_id=redacted".data(using: .utf8)!)
postData.append("&client_secret=redacted".data(using: .utf8)!)

    let request = NSMutableURLRequest(url: NSURL(string: "https://redacted.com/api/oauth2/token/")! as URL,
                                      cachePolicy: .useProtocolCachePolicy,
                                      timeoutInterval: 10.0)
    request.httpMethod = "POST"
    request.allHTTPHeaderFields = headers
    request.httpBody = postData as Data
    let session = URLSession.shared
    let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
        if (error != nil) {
            print(error)
        } else {
            let httpResponse = response as? HTTPURLResponse
            print(httpResponse)
        }
    })

当我单步执行 iOS 代码时,NSMutableData 和 Data 对象都将用户名正确显示为“[电子邮件受保护] /cdn-cgi/l/email-protection“,只是将 URLSession.shared 作为潜在的错误原因。但我无法进入 URLSession.shared.dataTask(),因为它是私有方法。任何帮助都会受到赞赏。


“+”字符的编码存在一些问题。你可以尝试这个:

let postData = NSMutableData(data: "username=james%[email protected] /cdn-cgi/l/email-protection".data(using: .utf8)!) 
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

iOS UrlSession.shared.dataTask 删除 utf-8“+”字符并替换为“” 的相关文章

随机推荐