swift - Alamofire 表单编码的 POST 请求因 responseSerializationFailed 而失败

标签 swift alamofire

使用 Alamofire (swift 4) 向 api 端点(表单编码内容类型)发出请求,并通过登录传递用户名和密码。在 POSTMAN 中进行测试时,此端点可以正常工作并返回有效的 JSON(见下文)。

enter image description here

我的swift代码如下:

let headers = [
  "content-type": "application/x-www-form-urlencoded",
   "cache-control": "no-cache"
 ]
let parameters = [
   "username": "user@user.com", 
   "password": "password"
 ]
 Alamofire.request("https://xxxxx.com/api/login/", method: .post, parameters: parameters, encoding:  JSONEncoding.default, headers: headers).responseJSON { response in
   print(response)
 }

我得到的响应如下:

FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))

如有任何见解,我们将不胜感激!

最佳答案

JSONEncoding.default 更改为 URLEncoding.default,如下所示,

Alamofire.request("https://xxxxx.com/api/login/", method: .post, parameters: parameters, encoding:  URLEncoding.default, headers: headers).responseJSON { response in
   print(response)
}

关于swift - Alamofire 表单编码的 POST 请求因 responseSerializationFailed 而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52395136/

相关文章:

Swift 3 - 异步请求表为空,刷新后填充

json - Alamofire - 将通用响应对象从 JSON 序列化为模型,无需强制解包

ios - 如何分别使用 Alamofire 发送参数和正文?

ios - Core Image Kernel Language 的 OpenGL 坐标系

ios - 在具有多个 TableView 的 View Controller 中删除 UITableView 行(Swift)

ios - 如何在 ios Swift 中从 Google Places API 获取坐标

swift - 无法将 Alamofire 添加到 Swift 项目

ios - 使用 xcode 6 beta6 和部署目标 7.0 的链接器命令失败,退出代码为 1(使用 -v 查看调用)

具有多种功能的 Swift 4 NSExpression

ios - 尝试使用 HealthKit 获取步数,但它总是返回 0.0