iOS UrlSession.shared.dataTask removes utf-8 “+” character and replaces it with “ ”

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-12 21:16:34

问题


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)
        }
    })

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.


回答1:


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)!) 


来源:https://stackoverflow.com/questions/46762155/ios-urlsession-shared-datatask-removes-utf-8-character-and-replaces-it-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!