iOS Swift POST api with x-www-form-urlencoded
iOS Swift POST api with x-www-form-urlencoded
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)
prettyPrinted
JSONSerialization.data(withJSONObject: postData, options: )
jsonString
"{"email":"example@domain.com"}
jsonString
Why don't you simply use "application/json" in "Content-Type".
– sohan vanani
Jun 29 at 11:36
3 Answers
3
Try this
var request = URLRequest(url: URL(string: strURL)!)
request.httpMethod = "POST"
let params = ["email":"example@domain.com"]
let postString = params
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringCacheData
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
DispatchQueue.main.async {
guard let data = data, error == nil else {
print(error! as NSError)
return
}
do {
let jsonDic = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:AnyObject]
success(jsonDic! as NSDictionary)
} catch {
print(error as NSError)
}
}
}
task.resume()
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"]
Share you API call response or error you are getting as images are not properly attached.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
JSONSerialization.data(withJSONObject: postData, options: .prettyPrinted)
. Don't useprettyPrinted
, that's adding line breaks which aren't useful. UseJSONSerialization.data(withJSONObject: postData, options: )
instead. Also, I'm wondering if you don't have infant a JSON inside JSON. MeaningjsonString
needs to be"{"email":"example@domain.com"}
, because clearly, naming that varjsonString
when it's a Dictionary, that's misleading, but the POSTMAN could say so.– Larme
Jun 29 at 11:18