I'm trying to send a POST request in my app. But server response 400. I tried to use solutions from string varient and json varient. Both cases I'm getting error code 400, but if I send same request via postman it response 200, and works properly. Server API using "http" and I set plist properties for it.
func requestSmsCode() {
let postUrl = URL(string: "http://www.myServer.com/auth/send_phone")
var request = URLRequest(url: postUrl!)
request.httpMethod = "POST"
let postString = "phone=myPhone"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
}
task.resume()
}
func requestSmsCodeWithJSON() {
let json: [String: Any] = ["phone": "myPhone"]
let jsonData = try? JSONSerialization.data(withJSONObject: json)
let url = URL(string: "http://www.myServer.com/auth/send_phone")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "No data")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
if let responseJSON = responseJSON as? [String: Any] {
print(responseJSON)
}
}
task.resume()
}