ios - 如何在 swift 中在 POST 请求参数中发送字符串键和 json 值?
问题描述
我想在 POST 中发送一个请求参数,其中键是字符串格式,值是 json 格式,如下所示:
request parameter : data={"firstName":"Pooja"}
请在 swift 4.1 中找到以下代码片段
let myUrl = URL(string: chatService)
print(myUrl)
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"// Set POST method
request.addValue("Content-Type", forHTTPHeaderField: "application/x-www-form-urlencoded")
let postString = 'data={"firstName":"Pooja"}'
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = defaultSession.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
解决方案
let url = URL(string: "http://www.thisismylink.com/postName.php")!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField:"Content-Type")
request.httpMethod = "POST"
let postString = "id=13&name=Jack"
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()}
使用上面的代码
推荐阅读
- java - 为什么我不能将最终的 long 分配给 int?
- swift - SwiftUI:强制更新
- oracle - 用于读取嵌套 JSON 数据的 Oracle 查询
- powershell - 使用轻度匹配搜索复制位于多个子文件夹中的文件
- python-3.x - 用 theano 解决 pymc3 中的简单化学网络 odes
- pyspark - 如何在 databricks 中读取 kaggle zip 文件数据集
- html - 对齐div中的元素
- c++ - 需要澄清使用 Boost asio 的 SSL 客户端
- r - 通过循环迭代单向方差分析会在 R 中引发错误
- node.js - 为什么我在所有 meanstack 项目中不断收到相同的错误:无法加载资源:net::ERR_CONNECTION_REFUSED