iOS UrlSession.shared.dataTask 删除 utf-8 “+"字符并将其替换为 ""字符、并将其、shared、UrlSession

2023-09-07 11:08:50 作者:妖未成精

我正在使用 x-www-form-endoded 数据创建对 API 的登录调用.我在 Postman 中创建了一个 POST 并收到 200 响应.我使用 Postman 的导出功能为 Android 生成 OKHTTP 代码和为 iOS 生成 NSURL 代码.Android 代码工作正常,但 iOS 代码收到 401 响应.我使用 Charles Web 调试代理来查看实际为有效负载发送的内容.对于 android,用户名正确表示为username=james+jypsee@jypsee.com",但在 iOS 中显示为username=james jypsee@jypsee.com".我的 iOS 代码如下:

I'm creating a login call to an API using x-www-form-endoded data. I created a POST in Postman and received a 200 response. I used Postman's export function to generate the OKHTTP code for Android and NSURL code for iOS. The Android code works fine, but the iOS code receives a 401 response. I used Charles web debugging proxy to look at what was actually being sent for the payload. For android the username is correctly represented as "username=james+jypsee@jypsee.com" but in iOS it comes out as "username=james jypsee@jypsee.com". My iOS code is below:

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

let postData = NSMutableData(data: "username=james+jypsee@jypsee.com".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 对象都正确地将用户名显示为username=james+jypsee@jypsee.com",只是将 URLSession.shared 作为潜在的错误原因.但我不能进入 URLSession.shared.dataTask() 因为它是一个私有方法.任何帮助表示赞赏.

When I stepped through the iOS code both the NSMutableData and Data objects correctly displayed the username as "username=james+jypsee@jypsee.com", just leaving the URLSession.shared as the potential cause of error. But I can't step into URLSession.shared.dataTask() because its a private method. Any help is appreciated.

推荐答案

+"字符的编码存在一些问题.你可以试试这个:

There is some issue with encoding of "+" characters. You can try this instead:

let postData = NSMutableData(data: "username=james%2Bjypsee@jypsee.com".data(using: .utf8)!)