Alamofire表单编码的POST请求失败,带有responseSerializationFailed

时间:2018-09-18 21:56:00

标签: swift alamofire

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

enter image description here

我的快捷代码如下:

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

任何见识将不胜感激!

1 个答案:

答案 0 :(得分:1)

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)
}
相关问题