I'm just trying to send simple variable to server using post request and I want to do it manually. Here is my code
guard let url = URL(string: urlString "/someapi") else {
return
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue(String(3), forHTTPHeaderField:"Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("text/plain", forHTTPHeaderField: "Accept")
var httpBody:Data=Data()
httpBody.append(contentsOf: "f=1".data(using: .utf8)!) //f is key & 1 value
request.httpBody = httpBody
let onComplete = {
(data:Data?,urlresponse:URLResponse?,error:Error?)->Void in
//do nothing
if let _ = error {
print("Error occured")
}
}
let task = session.dataTask(with: url, completionHandler: onComplete)
task.resume()
I'm using flask server to test this out. On flask side I analysed the request here is the it's header content
Accept: */*
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Accept-Encoding: gzip, deflate
User-Agent: Find Doctor/1 CFNetwork/1333.0.4 Darwin/21.4.0
And also flask server is receiving GET request instead of POST and also variables are not showing in server.
CodePudding user response:
You are not running dataTask with POST request
you specified in code, but rather doing simple GET on url (as was said in comments.) You should run task
with request.
let task = session.dataTask(with: request, completionHandler: onComplete)
task.resume()