如何使用Alamofire来实现API的post方法cURL请求?

时间:2019-07-02 04:59:41

标签: ios swift alamofire

我有cURL

curl --location --request POST "{{local_url}}/api/customer/registeration" \
  --header "Content-Type: application/x-www-form-urlencoded" \
  --header "device_id: jhjkhkjh" \
  --header "device_type: android" \
  --header "client_id: 1" \
  --header "client_secret: DdoCiociSYHlrjkFrfwfAaNdJcFLjy676ff017zt" \
  --data "name=ram&last_name=sham&mobile_number=7529883763&password=1&role_customer=home%20customer"

我想要在Swift中使用Alamofire进行注册的API实现,请帮助我。我尝试了以下代码,但收到错误代码422。请帮助我解决此问题。

    let urlString = "{{local_url}}/api/customer/registeration"
            let parameters: [String: Any] = ["name":"Prashant", "last_name": "Kumar", "mobile_number":7814802725, "password": 1, "role_customer": "home%20customer"]
        let headers = ["Content-Type": "application/x-www-form-urlencoded" ,"device_id": "jhjkhkjh", "device_type": "android", "client_id": "1", "client_secret": "DdoCiociSYHlrjkFrfwfAaNdJcFLjy676ff017zt"]
    Alamofire.request(urlString, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
                    if let json = response.result.value {
                        print(json)
                    }
                } 

但是我得到了结果。

{
    data =     {
    };
    error =     {
        code = 422;
        "error_message" =         {
            message =             (
                "The name field is required.",
                "The last name field is required.",
                "The mobile number field is required.",
                "The password field is required.",
                "The role customer field is required."
            );
        };
    };
    status = 0;
}

1 个答案:

答案 0 :(得分:0)

您的编码错误。 JSONEncoding.default用于当您要发送JSON数据而当前正在发送表单数据时。尝试使用

URLEncoding.default