我试图使用Alamofire发出如下API请求:
<%= link_to 'Nouvelle partie', games_path, method: :post, class: 'regular-btn' %>
我收到了此回复:
let param = ["id":"xy", "products":[["quantity":2, "product":["id":123]]]]
Alamofire.request(url, method: .post,
parameters: param, encoding: URLEncoding.default,
headers: ["Accept": "application/json", "Content-Type": "application/json"]).responseJSON ..
我也尝试过这样的请求:
message = "Unexpected token i in JSON at position 0";
statusCode = 400;
我尝试手动执行以下请求,以确保其运行正常:
request.httpBody = try! JSONSerialization.data(withJSONObject: param)
根据需要,它给了我以下答复:
curl -X POST http://url -d'{"id":"xy", "products" [{"quantity":2,"product":{"id":123}}]}' -H'Content-Type: application/json'
答案 0 :(得分:2)
您需要以application/json
的形式发送请求,所以请使用JSONEncoding.default
作为encoding
的参数。
Alamofire.request( url, method: .post , parameters: param, encoding: JSONEncoding.default , headers: ["Accept": "application/json",
"Content-Type": "application/json"])
附加组件:另外,您可以从标头参数中删除Content-Type
。 AF
会为您解决这个问题。