1

I have to make an API call with headers as "application/x-www-form-urlencoded" and in body "data" as key and vakue as a JSON string. I have to pass the data as application/x-www-form-urlencoded format. I have attached the screenshot of postman where it is working fine.

[image with headers marked][image with post data as x-www-form-urlencoded marke]

I have tried many links like POST request using application/x-www-form-urlencoded. But couldn't find a correct one.

I'm fine to use other frameworks like Alamofire to solve this issue.

I'm using the below code for this.

    let url = URL(string: "http://mylocalhost/get-user-details")!
    var request = URLRequest(url: url)
    let jsonString = ["email":"example@domain.com"]
    let postData = ["data":jsonString]
    let jsonData = try! JSONSerialization.data(withJSONObject: postData, options: .prettyPrinted)

    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.httpMethod = "POST"
    request.httpBody = jsonData

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {                                                 // check for fundamental networking error
            print("error=\(error)")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")
        }

        let responseString = String(data: data, encoding: .utf8)
        print("responseString = \(responseString)")
    }

    task.resume()
  • `JSONSerialization.data(withJSONObject: postData, options: .prettyPrinted)`. Don't use `prettyPrinted`, that's adding line breaks which aren't useful. Use `JSONSerialization.data(withJSONObject: postData, options: [])` instead. Also, I'm wondering if you don't have infant a JSON inside JSON. Meaning `jsonString` needs to be `"{\"email\":\"example@domain.com\"}`, because clearly, naming that var `jsonString` when it's a Dictionary, that's misleading, but the POSTMAN could say so. – Larme Jun 29 '18 at 11:18
  • Why don't you simply use "application/json" in "Content-Type". – sohan vanani Jun 29 '18 at 11:36

2 Answers2

0

If you are want to use Alamofire then use this method.

 func request(_ method: HTTPMethod
    , _ URLString: String
    , parameters: [String : AnyObject]? = [:]
    , headers: [String : String]? = [:]
    , onView: UIView?, vc: UIViewController, completion:@escaping (Any?) -> Void
    , failure: @escaping (Error?) -> Void) {

    Alamofire.request(URLString, method: method, parameters: parameters, encoding: URLEncoding.default, headers: headers)
        .responseJSON { response in


            switch response.result {
            case .success:
                completion(response.result.value!)
            case .failure(let error):
                failure(error)
                guard error.localizedDescription == JSON_COULDNOT_SERIALISED else {

                    return
                }
            }
    }
}

Pass this in header parameter

["Content-Type": "application/x-www-form-urlencoded"]
Manish Mahajan
  • 2,062
  • 1
  • 13
  • 19
0

This worked for me, replace your 6th line by this:

request.setValue("application/json", forHTTPHeaderField: "Content-Type")
Shaher Kassam
  • 252
  • 2
  • 12