我是 swift 的新手,我试图向网站发出发布请求,但还没有得出有效的结果。我发现的所有示例也不适合我。
我需要发送一个 json 正文给 https://mypostrequestdestination.com/api/
json body 只包含一个值
{State:1}
Header 必须包含
{"Authorization": bearer "token"}
{"Accept":"application/json"}
{"Content-Type":"application/json"}
希望有人能帮助我。
谢谢!
最佳答案
这个对我有用
let token = "here is the token"
let url = URL(string: "https://mypostrequestdestination.com/api/")!
// prepare json data
let json: [String: Any] = ["State": 1]
let jsonData = try? JSONSerialization.data(withJSONObject: json)
// create post request
var request = URLRequest(url: url)
request.httpMethod = "POST"
// insert json data to the request
request.httpBody = jsonData
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.setValue( "Bearer \(token)", forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "No data")
return
}
let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
if let responseJSON = responseJSON as? [String: Any] {
print(responseJSON)
}
}
task.resume()
关于json - 在 Swift 中发送带有承载 token 和 json 正文的发布请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52347576/