将json参数发布到api使用post方法Swift 3
Posted
技术标签:
【中文标题】将json参数发布到api使用post方法Swift 3【英文标题】:posting json parameter to api use post method Swift 3 【发布时间】:2017-05-27 04:57:17 【问题描述】:我需要将以下 json 传递给此函数,以便 Shopify Api 可以理解提交。我无法创建正确的变量格式并将其传递给服务器。Shopify API 期望通过 POST 传递以下 json
【问题讨论】:
【参考方案1】:将 REQUEST_URL 替换为您的 API URL
将 JSON_STRING 替换为您的实际 json 字符串
var request = URLRequest(url: URL(string: "REQUEST_URL")!)
request.httpMethod = "POST"
let postString = "JSON_STRING"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) data, response, error in
guard let data = data, error == nil else // check for fundamental networking error
print("error=\(error)")
return
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
task.resume()
将您的对象转换为字典,然后将其序列化
do
let data = try JSONSerialization.data(withJSONObject: dict, options: [])
postString = String.init(data: data, encoding: String.Encoding.utf8)!
catch
print(error)
【讨论】:
parth 你能告诉我如何在 'let poststring = "Json_strong" 中设置我的 json 字符串吗?? 你有你的数据或对象的json字符串吗? 对象parth兄弟 然后你可以将你的对象转换成字典形式,然后使用json序列化进行序列化以上是关于将json参数发布到api使用post方法Swift 3的主要内容,如果未能解决你的问题,请参考以下文章
如何将参数从 POST 从 Amazon API Gateway 传递到 AWS Lambda
当我们在ColdFusion中使用API 调用(POST请求)将参数数量传递给服务器时,如何修复“POST请求超出”错误?
如何将类型的对象作为参数传递给Web Api Get / Post方法