我正在尝试使用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协议似乎工作正常
答案 0 :(得分:2)
好的,这是我看到的一些事情。
将POST发送到服务器时,URL必须是Web Service或某种Web应用程序。在这里,您似乎正在尝试POST到资源文件。静态资源文件不会自动更新。
您没有指定编码,因此您没有发布JSON(application / json),您发布了表单URL编码(application / x-www-form-urlencoded)。您发送了{ "name": "Danial" }
。
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)")
}
}
}