gpt4 book ai didi

swift - 如何在 swift 中执行 curl 请求?

转载 作者:搜寻专家 更新时间:2023-10-31 19:32:04 25 4
gpt4 key购买 nike

我正在尝试使用外部 API,它的 API 请求如下所示。我习惯了只有一个 url 的请求,但是我如何处理“H”和“d”参数?我应该将它们包含在我的网址中还是

$ curl -X POST https://api.lucidtech.ai/v0/receipts \
-H 'x-api-key: <your api key>' \
-H 'Content-Type: application/json' \
-d '{"documentId": "a50920e1-214b-4c46-9137-2c03f96aad56"}'

目前我有以下代码,但我应该将 API key 和文档 ID 放在这段代码的什么位置?

@IBAction func getScannedData(_ sender: Any){
guard let url = URL(string: "https://api.lucidtech.ai/v0/receipts") else {return}

let session = URLSession.shared
session.dataTask(with: url) { (data, response, error) in
if let response = response{
print(response)
}


}

最佳答案

这是一个示例,说明如何将 curl 命令转换为 URLRequest:

guard let url = URL(string: "https://api.lucidtech.ai/v0/receipts"),
let payload = "{\"documentId\": \"a50920e1-214b-4c46-9137-2c03f96aad56\"}".data(using: .utf8) else
{
return
}

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("your_api_key", forHTTPHeaderField: "x-api-key")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = payload

URLSession.shared.dataTask(with: request) { (data, response, error) in
guard error == nil else { print(error!.localizedDescription); return }
guard let data = data else { print("Empty data"); return }

if let str = String(data: data, encoding: .utf8) {
print(str)
}
}.resume()

关于swift - 如何在 swift 中执行 curl 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52032108/

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