[英]iOS UrlSession.shared.dataTask removes utf-8 "+" character and replaces it with " "
I'm creating a login call to an API using x-www-form-endoded data.我正在使用 x-www-form-endoded 数据创建对 API 的登录调用。 I created a POST in Postman and received a 200 response.
我在 Postman 中创建了一个 POST 并收到了 200 个响应。 I used Postman's export function to generate the OKHTTP code for Android and NSURL code for iOS.
我使用 Postman 的导出功能生成了 Android 的 OKHTTP 代码和 iOS 的 NSURL 代码。 The Android code works fine, but the iOS code receives a 401 response.
Android 代码运行良好,但 iOS 代码收到 401 响应。 I used Charles web debugging proxy to look at what was actually being sent for the payload.
我使用 Charles Web 调试代理来查看实际为有效负载发送的内容。 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".
对于 android,用户名正确表示为“username=james+jypsee@jypsee.com”,但在 iOS 中,它显示为“username=james jypsee@jypsee.com”。 My iOS code is below:
我的iOS代码如下:
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)
}
})
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.当我单步执行 iOS 代码时,NSMutableData 和 Data 对象都正确地将用户名显示为“username=james+jypsee@jypsee.com”,只是将 URLSession.shared 作为潜在的错误原因。 But I can't step into URLSession.shared.dataTask() because its a private method.
但是我不能进入 URLSession.shared.dataTask() 因为它是一个私有方法。 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)!)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.