当尝试通过http向服务器发送post数据时,它不返回post数据。下面是一个示例代码:
var request = URLRequest(url: URL(string: "http://posttestserver.com/post.php")!)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let json = "{\"key\":\"c7cbdc09820372\",\"rand\": \"13baa5274c2b107727\"}"
request.httpBody = json.data(using: .utf8)
URLSession.shared.dataTask(with: request) { (data, response, error) in
if data != nil, let result = String(data: data!, encoding: .utf8) {
print("\(result)")
}
}.resume()
结果是:
已成功转储0个发布变量...无柱体。
3条答案
按热度按时间syqv5f0l1#
这段代码可以工作,如果有人需要:
提供:
已成功转储2个post变量....
nkoocmlb2#
将你的json字符串转换成字典,然后
jsonData = try?JSONSerialization.data(withJSONObject:dict,选项:.prettyPrinted)
request.httpBody = jsonData
c9x0cxw03#
我认为最好的函数为http post/get request params =“param 1 =value¶m2= value 2”如果你想使用json你应该改变为Content-Type值不要忘记