📜  快速 url 请求 - Swift 代码示例

📅  最后修改于: 2022-03-11 15:01:00.704000             🧑  作者: Mango

代码示例2
let Url = String(format: "http://10.10.10.53:8080/sahambl/rest/sahamblsrv/userlogin")
    guard let serviceUrl = URL(string: Url) else { return }
    let parameters: [String: Any] = [
        "request": [
                "xusercode" : "YOUR USERCODE HERE",
                "xpassword": "YOUR PASSWORD HERE"
        ]
    ]
    var request = URLRequest(url: serviceUrl)
    request.httpMethod = "POST"
    request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
    guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else {
        return
    }
    request.httpBody = httpBody
    request.timeoutInterval = 20
    let session = URLSession.shared
    session.dataTask(with: request) { (data, response, error) in
        if let response = response {
            print(response)
        }
        if let data = data {
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: [])
                print(json)
            } catch {
                print(error)
            }
        }
    }.resume()
}