ios - Alamofire POST 错误请求

标签 ios swift3 alamofire

我正在尝试通过 Alamofire 向我的服务器发出发布请求,但它返回一个错误请求,表示参数格式错误。相同的请求在 postman 和招摇中工作。

代码如下:

var params = [
            "username": "jora@company.com",
            "password": "test123",
            "pushToken": "No token"
    ]

Alamofire.request("https://thankyouposta.com/api/auth", method: .post, parameters: params, encoding: URLEncoding.default, headers: R.Api.headers).responseJSON { response in
        switch response.result {
        case .success(let value):
            // ...
        case .failure(let error):
            // ...
        }
    }

更新 1

参数需要作为表单 url 编码正文发送

更新 2

R.Api.headers 的值为

["Content-Type" : "application/x-www-form-urlencoded"]

最佳答案

如果你想以 form-urlencoded 的形式发送请求,你应该把它作为一个标题并改变你的编码:

let headers = [
                "Content-Type": "application/x-www-form-urlencoded"
            ]
        var params = [
            "username": "jora@company.com",
            "password": "test123",
            "pushToken": "No token"
    ]

        Alamofire.request("your_url_here", method: .post, parameters: parameters, encoding:  URLEncoding.httpBody, headers: headers).responseJSON { response  in 
}

关于ios - Alamofire POST 错误请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47000491/

相关文章:

swift3 - 在 Alamofire 请求的正文中发送 JSON 数据

swift - 如何正确安装 Alamofire SwiftyJSON 和 Alamofire-SwiftyJson

ios - UIPageViewController 手势识别器

ios - CGImageCreateWithImageInRect() 返回零

ios - 如何从设备中的图像读取二维码

swift - 甚至未使用的参数的通用 T.Type 和逗号分隔的约束

json - 使用 SwiftyJSON 解析 Alamofire JSON 结果

ios - Collectionview 在快速选择新行时取消选择所选行

iphone - 登录页面

ios - UITableViewCell 的动态高度计算取决于 TextView 的高度