簡體   English   中英

在Swift中使用承載令牌和json正文發送發布請求

[英]Send post request with bearer token and json body in Swift

我是新手,很快就嘗試向網站提出發布請求,但還沒有得出一個可行的結果。 我發現的所有示例都不適合我。

我需要將JSON正文發送到https://mypostrequestdestination.com/api/

json正文僅包含一個值

{State:1}

並且標題必須包含

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM