如何在Swift 4中发送HTTP请求?

时间:2017-07-25 09:04:36

标签: swift swift3 swift4

Swift 4有什么变化吗?在swift 3中我使用了这段代码

    var request = URLRequest(url: URL(string: "http://www.centill.website/ajax/logreg.php")!)
    request.httpMethod = "POST"
    let postString = "ko=1231a"
    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)
        }

        let responseString = String(data: data, encoding: .utf8)
        print(responseString)
    }
    task.resume()

我想知道他们是否做了任何改进或添加了任何新内容。

1 个答案:

答案 0 :(得分:-2)

尝试使用此

            let strMethod = String(format : "http://www.centill.website/ajax/logreg.php" )

            let params: [String : Any] = ["ko": "1231a"]
            print(params)

            let url = URL(string: strMethod)!

            let data = try! JSONSerialization.data(withJSONObject: params, options: JSONSerialization.WritingOptions.prettyPrinted)

            let json = NSString(data: data, encoding: String.Encoding.utf8.rawValue)

            if let json = json {  print(json) }

            let jsonData = json!.data(using: String.Encoding.utf8.rawValue);

            var request = URLRequest(url: url)
            request.httpMethod = HTTPMethod.post.rawValue
            request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")

            request.httpBody = jsonData

            Alamofire.request(request).responseJSON {  (response) in
                switch response.result {
                    case .success(let JSON2):
                       print("Success with JSON: \(JSON2)")                        
                       break

                    case .failure(let error):
                       print("Request failed with error: \(error)")
                       //callback(response.result.value as? NSMutableDictionary,error as NSError?)
                        break
                    }
                }
                .responseString { response in
                    print("Response String: \(response.result.value)")
            }