Swift 发送 GET/POST 请求

GET

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
var urlComponents = URLComponents(string: "your url")!

// 查询条件
urlComponents.queryItems = [
URLQueryItem(name: "collection", value: "map")
]

var request = URLRequest(url: urlComponents.url!)

// or
// let url = URL(string: "your url")!
// var request = URLRequest(url: url)

request.httpMethod = "GET"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
// 查询时可能需要加入 token 验证权限
request.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")

let task = URLSession.shared.dataTask(with: request) { (data, response, error) in

guard error == nil else {
print("Error: \(error!)")
return
}

guard let data = data else {
print("data is nil")
return
}

guard let responseString = String(data: data, encoding: .utf8) else {
print("the response is not in UTF-8")
return
}

logger.info("API Response: \(responseString)")

do {
let result = try JSONDecoder().decode(Result.self, from: data)
// 处理解析后的数据
} catch {
logger.error("API: \(error.localizedDescription)")
}
}
task.resume()

URLComponents 参考:Swift GET request with parameters

POST

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
let url = URL(string: "your url")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
// 请求时可能需要 token 验证权限
request.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")

let parameters = ["key1": value1, "key2": value2]

do {
let jsonData = try JSONEncoder().encode(parameters)
request.httpBody = jsonData

let task = URLSession.shared.dataTask(with: request) { (data, response, error) in

guard error == nil else {
print("Error: \(error!)")
return
}

guard let data = data else {
print("data is nil")
return
}

guard let responseString = String(data: data, encoding: .utf8) else {
print("the response is not in UTF-8")
return
}

logger.info("API Response: \(responseString)")

do {
let result = try JSONDecoder().decode(CreateRoomResult.self, from: data)
// 处理解析后的数据
} catch {
logger.error("API: \(error.localizedDescription)")
}
}

task.resume()

} catch {
logger.error("API: \(error.localizedDescription)")
}

关于 post 需要特别注意的是,如果 parameters 的 value 为不同格式:

1
let parameters = ["key1": Int, "key2": String] as [String : Any]

此时再使用 JSONEncoder() 则会报错提示 Type 'Any' cannot conform to 'Encodable'。解决办法是定义一个遵循 Codable 协议的结构:

1
2
3
4
struct Parameters: Codable {
let key1: Int
let key2: String
}

之后再:

1
let parameters = Parameters(key1: Int, key2: String)

或者直接使用

1
2
3
let jsonData = try JSONSerialization.data(withJSONObject: parameters)
// 替换
// let jsonData = try JSONEncoder().encode(parameters)

Swift 发送 GET/POST 请求
https://wonderhoi.com/2024/11/29/Swift-发送-GET-POST-请求/
作者
wonderhoi
发布于
2024年11月29日
许可协议