作者:徐青乔府_631 | 来源:互联网 | 2022-12-04 18:12
我是新手,很快就尝试向网站提出发布请求,但还没有得出一个可行的结果。我发现的所有示例都不适合我。
我需要将JSON正文发送到https://mypostrequestdestination.com/api/
json正文仅包含一个值
{State:1}
并且标题必须包含
{"Authorization": bearer "token"}
{"Accept":"application/json"}
{"Content-Type":"application/json"}
希望可以有人帮帮我。
谢谢!
1> Mason..:
这个为我工作
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()