Alamofire张贴json和回应json

时间:2017-06-11 15:34:57

标签: ios json swift alamofire

我尝试使用Swift3和Alamofire发布JSON,它在Postman Postman screen shot中成功运行 但在代码中,响应是HTML字符串,这意味着服务器中的异常 我尝试将编码从JsonEncoding.default更改为URLEncoding.default并且效果很好,但在运行应用程序后3天内出现相同的错误

let url = "http://mattam.net/mobileapp/addOrder"
let par:[String:Any] = ["order_restaurant":8,
                                 "order_type":1,
                                 "order_address":1,
                                 "order_within":"45 mins",
                                 "order_exacttime":"09:00 pm",
                                 "order_total":300,
                                 "order_fees":30,
                                 "order_gtotal":330,
                                 "order_user":38,
                                 "pquantity[10]":3,
                                 "pquantity[9]":1,
                                 "poption[9]":238,
                                 "pextra[10]":"80,81"]



        print(par)


        Alamofire.request(url, method: .post, parameters: par, encoding: URLEncoding.default).responseJSON{
                r in
                if r.result.isSuccess{print("------i______i-----")}
                print(r)
                if let result = r.result.value as? NSDictionary{
                    print(result)}

            }

并在PostMan批量编辑

order_restaurant:8
order_type:1
order_address:1
order_within:45 mins
order_exacttime:09:00 pm
order_total:300
order_fees:30
order_gtotal:330
order_user:38
pquantity[10]:3
pquantity[9]:1
poption[9]:238
pextra[10]:80,81

和url是“let url =”http://mattam.net/mobileapp/addOrder“”

3 个答案:

答案 0 :(得分:1)

您的问题是您在应用中使用http而不是https。 屏幕截图使用https,而您发布的网址(从您的代码中复制)使用http

答案 1 :(得分:0)

如果我理解你的问题,你需要将一些帖子详细信息作为Json发送到服务器,所以这里有一些代码:

private func alamoFireAjax(url: String, parameters: Parameters, callback: @escaping (DataResponse<Any>) -> Void) {
    Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON(completionHandler: callback)
}

答案 2 :(得分:0)

我遇到了类似的问题,为了解决这个问题,我将字典创建放在方法调用中。你通常可以逃避大多数请求,但我发现大于10行的任何东西需要一个单独的方法处理程序。

fileprivate func generateParams() -> [String: Any] {

    var params = [String: Any]()

    params["order_restaurant"] = 8
    params["order_type"] = 1
    params["order_address"] = 1
    params["order_within"] = "45 mins"
    params["order_exacttime"] = "09:00 pm"
    params["order_total"] = 300
    params["order_fees"] = 30
    params["order_gtotal"] = 330
    params["order_user"] = 38
    params["pquantity[10]"] = 3
    params["pquantity[9]"] = 1
    params["poption[9]"] = 238
    params["pextra[10]"] = "80,81"

    return params

}