在Swift中使用Bearer令牌和JSON主体发送POST请求。

16

我对Swift还比较陌生,尝试向一个网站发送POST请求,但是还没有得到工作的结果。所有我找到的例子都没有起作用。

我需要发送一个JSON主体到https://mypostrequestdestination.com/api/

JSON主体仅包含一个值。

{State:1}

并且标题必须包含

{"Authorization": bearer "token"}

{"Accept":"application/json"}

{"Content-Type":"application/json"}

希望有人能够帮助我。

谢谢!

1个回答

35

这个对我有用

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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接