伺服器要求 JSON 物件(以 {} 包裹),而非裸鍵值對。iOS 需將 Dictionary 序列化為 JSON Data,並設定正確的 Content-Type。
let url = URL(string: "https://api.example.com/endpoint")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
let body = ["HomeType": "1"] // Dictionary
do {
request.httpBody = try JSONSerialization.data(withJSONObject: body, options: [])
} catch {
print("JSON 序列化失敗: \(error)")
return
}
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error { print("請求失敗: \(error)"); return }
guard let httpResponse = response as? HTTPURLResponse else { return }
print("狀態碼: \(httpResponse.statusCode)")
if let data = data, let str = String(data: data, encoding: .utf8) {
print("回應: \(str)")
}
}
task.resume()
| 項目 | 正確值 | 錯誤示範 |
|---|---|---|
| HTTP Method | POST | GET |
| Content-Type | application/json | application/x-www-form-urlencoded |
| Body 資料 | JSONSerialization.data(from: dict) | 字串拼接 "{HomeType:1}" |
| 大括號 | JSON 物件自動包含 | 手動拼接易漏逗號/引號 |
struct RequestBody: Codable {
let homeType: String
enum CodingKeys: String, CodingKey { case homeType = "HomeType" }
}
let body = RequestBody(homeType: "1")
request.httpBody = try JSONEncoder().encode(body)
// JSONEncoder 輸出: {"HomeType":"1"}
JSONSerialization 預設 UTF-8,正常;若手動拼接字串需 .data(using: .utf8)。// 印出實際發送的 JSON 字串
if let body = request.httpBody,
let jsonStr = String(data: body, encoding: .utf8) {
print("將發送: \(jsonStr)")
}
使用 JSONSerialization 或 JSONEncoder 將 Dictionary/Model 轉為 Data,設定 Content-Type: application/json,即可產生帶大括號的標準 JSON Body,滿足伺服器需求。