当我使用swift发布json时,如何解析http代码412和200?

时间:2017-10-04 09:55:17

标签: json swift dictionary alamofire

我正在尝试使用swift(Alamofire)向本地主机中的json文件发送一个非常简单的字典 这就是我所做的:

let parameters: Parameters = ["name" : "Danial"]


        Alamofire.request("http://localhost/testing.json", method: HTTPMethod.post, parameters: parameters).response { result in
            if result.response?.statusCode != nil {
                 if let status =  (result.response?.statusCode)! as? Int {

                    print("status : \(status)")
                }
            }

        }

在我的testing.json中,我有以下内容:

{  
   "x":"y"
}

我很少得到http状态412(经常)和200(没有在json文件中出现新的json)。我对这个网络的东西很新。因此,请不要攻击我的问题,好像我必须知道这个简单的事情。这已经花了我两天的时间来解决我在这里:| 顺便说一句,连接应该没有错误,因为我的get协议似乎工作正常

1 个答案:

答案 0 :(得分:2)

好的,这是我看到的一些事情。

  1. 将POST发送到服务器时,URL必须是Web Service或某种Web应用程序。在这里,您似乎正在尝试POST到资源文件。静态资源文件不会自动更新。

  2. 您没有指定编码,因此您没有发布JSON(application / json),您发布了表单URL编码(application / x-www-form-urlencoded)。您发送了{ "name": "Danial" }

  3. ,而不是name=Danial

    您需要将编码设置为JSON。

    let parameters: Parameters = ["name" : "Danial"]
    
    Alamofire.request("http://localhost/testing.json",
                      method: HTTPMethod.post,
                      parameters: parameters,
                      encoding: JSONEncoding.default).response { result in
        if result.response?.statusCode != nil {
            if let status =  (result.response?.statusCode)! as? Int {
                print("status : \(status)")
            }
        }
    }