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()