【发布时间】:2019-09-17 23:18:48
【问题描述】:
我正在尝试将这些参数作为发布请求发送到 URL,但未发送参数。我不知道是否是URLSession 配置问题。任何人都可以检查并解决问题吗?
import UIKit
let json: [String: Any] = [
"set_id" : "20",
"user_id" : "30",
"type" : "contact",
"contact_name" : "shinto"
]
let jsonData = try? JSONSerialization.data(withJSONObject: json)
var str = String(data: jsonData!, encoding: .utf8)
let url = URL(string: "****.php")!
var request = URLRequest(url: url)
request.httpMethod = "Post"
request.httpBody = str!.data(using: .utf8)
let session = URLSession(configuration: .default)
let task = session.dataTask(with: request) {
(data, response, error) in
if let data = data {
if let postResponse = String(data: data, encoding: .utf8) {
print(postResponse)
}
}
}
task.resume()
【问题讨论】:
-
request.httpBody = str!.data(using: .utf8)为什么不直接做request.httpBody = jsonData?现在你怎么知道“参数没有被发送”?另外,request.httpMethod = "Post"使用POST(全部大写?) -
@Larme 不工作兄弟
-
让 jsonData = 试试? JSONSerialization.data(withJSONObject: userID, options:.prettyPrinted) 作为数据。现在设置 request.httpBody = jsonData
-
你在标题中提到
Content-Type为json 吗? -
是的,我添加了一些自定义字段 var urlRequest = URLRequest(url: getOEMurl!) urlRequest.setValue("application/json", forHTTPHeaderField: "Accept") urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") urlRequest.setValue(String(format:"%f",(userIdJson?.count)!), forHTTPHeaderField: "Content-Length")
标签: ios swift xcode urlsession