1

I'm trying to parse a JSON from a post request but I need to pass the content as x-www-form-urlencoded. I'm using Alamofire and Swift5, the code used to perform the request is this:

public func performRequest(url: String, parameters: [String:String]){
        AF.request(url, method: .post, parameters: parameters, encoding: URLEncoding.httpBody).validate().responseJSON{ response in
            switch response.result {
            case .success(let JSON): // memorizza il file JSON di risposta in una variabile di nome JSON
                print("Validation Successful with response JSON \(JSON)")
            case .failure(let error):
                // print(error.localizedDescription)
            print("Request failed with error \(error)")
            }
        }
    }

How do I pass the content as x-www-form-urlencoded?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
V_49
  • 17
  • 4
  • 1
    Does this answer your question? [post application/x-www-form-urlencoded Alamofire](https://stackoverflow.com/questions/37177879/post-application-x-www-form-urlencoded-alamofire) – Vladyslav Shmatok Nov 17 '20 at 16:56
  • Your code seems to be correct. `URLEncoding` handles the parameter encoding and also adds the corresponding headers in the request. What is your issue here? You are getting an error? – gcharita Nov 17 '20 at 17:18

1 Answers1

2

You can achieve it to adding in header like :

let param:Parameters=[
        "param":param]
   let headers:HTTPHeaders=[
        "Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"]
    
    Alamofire.request(url,method: .post,parameters: param,encoding: URLEncoding.httpBody, headers: headers).responseJSON{response in
....
 }
Omer Tekbiyik
  • 4,255
  • 1
  • 15
  • 27