iOS UrlSession.shared.dataTask removes utf-8 “+” c

2019-07-11 18:02发布

问题:

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