在Swift中使用承载令牌和json正文发送发布请求

时间:2018-09-15 18:16:27

标签: json swift post request token

我是新手,很快就尝试向网站提出发布请求,但还没有得出一个可行的结果。我发现的所有示例都不适合我。

我需要将json正文发送到 https://mypostrequestdestination.com/api/

json主体仅包含一个值

{State:1}

标题必须包含

{"Authorization": bearer "token"}

{"Accept":"application/json"}

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

希望有人可以帮助我。

谢谢!

1 个答案:

答案 0 :(得分:2)

这对我有用

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