gpt4 book ai didi

json - Swift - 在 Post 请求上向 httpBody 添加参数

转载 作者:行者123 更新时间:2023-11-30 10:57:14 32 4
gpt4 key购买 nike

我正在向某个 URL 发帖,我的 webDev 告诉我需要设置

"data="

作为参数,我的 JSONObject 作为键。我不知道如何将字符串设置为参数。

我尝试在 request.httpBody 上连接一个字符串,但它只接受数据。我也尝试将其添加到其他一些区域,但没有成功。

let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
let dateString = dateFormatter.string(from: load.date)

let json: [String: Any] = ["lb_datetime": "\(dateString)", "operator_id": "\(load.operatorID)", "ticket_number": load.ticketNumber, "timber_sale_id": "\(load.saleID)", "hauler_id": haulerInt, "product_id": String(load.productID), "destination": load.destination, "driver": load.driver, "trailer": load.trailerNumber, "trailer_drop": "\(load.trailerDrop)", "scaleticket": load.scaleTicketNumber, "tons": "\(load.tons)", "coords": coordsString, "net": "\(load.net)", "live": "true"]

print("JSON Object: \(json)")

let jsonData = try? JSONSerialization.data(withJSONObject: json)

// create post request
let url = URL(string: "http://example.net/example/app/mobile/removal/")!
var request = URLRequest(url: url)
request.httpMethod = "POST"

// insert json data to the request
request.httpBody = jsonData

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("RESPONSEDATA: \(responseJSON)")
}
}

task.resume()

非常感谢任何帮助!

最佳答案

let jsonData = try? JSONSerialization.data(withJSONObject: json)
if let _jsonData = jsonData {
request.httpBody?.append(jsonData)
}

关于json - Swift - 在 Post 请求上向 httpBody 添加参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53823220/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com