您好,我想将 Curl POST api 集成到我的代码中,我对此没有任何想法,请指导我如何用 swift 语言集成它
下面的网络服务调用我已经集成到我的代码中,已经尝试过但没有得到结果
curl -X POST http://stf.rortechnologies.com/api/session.js --data '{"user": {"email":"XXXXXX", "password":"XXXXXX"}}' -H "Content-Type:application/json"
let parameters = ["email":"admin.test@stf.com", "password":"password"]
let header = ["user": parameters]
//create the url with URL
let url = URL(string: "http://stf.rortechnologies.com/api/session.js")! //change the url
//create the session object
let session = URLSession.shared
//now create the URLRequest object using the url object
var request = URLRequest(url: url)
request.httpMethod = "POST" //set http method as POST
do {
request.httpBody = try JSONSerialization.data(withJSONObject: header, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
} catch let error {
print(error.localizedDescription)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
//create dataTask using the session object to send data to the server
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
guard error == nil else {
return
}
guard let data = data else {
return
}
do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
print(json)
// handle json...
}
} catch let error {
print(error.localizedDescription)
}
})
task.resume()
这里得到空响应
最佳答案
应用传输安全 (ATS)
您正在调用 http url,而不是 https url。在生产中始终应使用 https。这是由 iOS 强制执行的。
出于测试目的,可以在 info.plist 中声明异常,可以在此处找到文档: https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW33
JSON 编码/解码
在 Swift 中,有一种使用 JSONEncode/JSONDecoder 来编码/解码 JSON 的便捷方法。一个简单的解决方案可能如下所示。
定义参数结构
struct Login: Encodable {
let user: User
}
struct User: Encodable {
let email: String
let password: String
}
定义返回结构
struct Result: Decodable {
//add expected JSON fields here
}
休息通话
private func makeRestCall() {
let login = Login(user: User(email: "admin.test@stf.com", password: "password"))
guard let loginJson = try? JSONEncoder().encode(login) else { return }
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
guard let url = URL(string: "<add some valid url here>") else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = loginJson
let dataTask = session.dataTask(with: request) { (data, response, error) in
if let response = response as? HTTPURLResponse {
if response.statusCode == 200 {
guard let data = data else {
print ("call failed - no data returned")
return
}
guard let result = try? JSONDecoder().decode(Result.self, from: data) else {
print ("json decoding failed")
return
}
print ("call succesfully returned \(result)")
} else {
print ("call failed with status \(response.statusCode)")
}
} else {
print ("call failed: no http response")
}
}
dataTask.resume()
}
checkin HTTPS 代理
为了确保发送正确的数据,您可以使用 HTTPS 代理软件。它看起来像这样:
关于iOS curl -X POST 集成在 swift 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53137602/