我正在使用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代码如下:
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(),因为它是一个私有方法。任何帮助表示赞赏。
答案 0 :(得分:2)
“+”字符的编码存在一些问题。你可以试试这个:
let postData = NSMutableData(data: "username=james%2Bjypsee@jypsee.com".data(using: .utf8)!)