gpt4 book ai didi

ios - 在 Swift 中通过 JSON 正文将字符串数组发布到 API

转载 作者:搜寻专家 更新时间:2023-11-01 05:31:32 24 4
gpt4 key购买 nike

我正在尝试将一个字符串数组上传到使用我本地数据库中的数据的 Edamam API。对于 API,我需要发布一个带有标签“ingr”的字符串数组,以便它能够识别它。我应该能够输入每种成分的 "\(mass) grams\(name)" 并得到一个可以分析所述成分的常量营养素的响应。我正在使用的代码:

API 配置:

func getData(strURL: String, dictParam: Dictionary<String, Any>, completion: @escaping(Dictionary<String, AnyObject>)->()) {

var request = URLRequest(url: URL(string: strURL)!)
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject: dictParam, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")

let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in
print(response!)
do {
let json = try JSONSerialization.jsonObject(with: data!) as! Dictionary<String, AnyObject>
print(json)
completion(json)
} catch {
print("error")
}
})
task.resume()
}

API 调用:

let dictParams = ["ingr":["100 grams apple"]] as Dictionary<String, Any>
APICalling.shared.getData(strURL: baseURL, dictParam: dictParams) { (response) in
action()
}
}

使用 Rested 应用程序时,我可以上传任意数量的成分,并且会得到格式正确的响应,一切都很好。但是,当我尝试在我的应用程序中实现代码时,它会打印“错误”:冲突。关于如何正确实现 API 调用的任何想法?

最佳答案

已找到问题的解决方案。在我的请求中添加了一些 header ,现在一切正常。

        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("*/*", forHTTPHeaderField: "Accept")
request.addValue("no-cache", forHTTPHeaderField: "Cache-Control")
request.addValue("api.edamam.com", forHTTPHeaderField: "Host")
request.addValue("gzip, deflate", forHTTPHeaderField: "Accept-Encoding")
request.addValue("keep-alive", forHTTPHeaderField: "Connection")

关于ios - 在 Swift 中通过 JSON 正文将字符串数组发布到 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58328013/

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