Question

I would like to send a POST request to an API with two parameters. How to start with it?

The API is https://www.google.com/
The parameters are

1
2
id = 1234
name = wei

Answer

Below is the example for Swift 3, you can follow with that.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var request = URLRequest(url: URL(string: "https://www.google.com/")!)
request.httpMethod = "POST"
let postString = "id=1234&name=wei"
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()

Reference


This is the end of post