request.httpBody和URLSession.share.upload(with:from :)有什么区别

时间:2019-01-06 02:34:04

标签: swift http post urlsession

我正在快速使用URLSession通过php将帖子发送到我的Web服务,该php从$ _POST [“ varname”]获取数据。

我发现将var放入request.httpBody起作用,并将var放入上载data(with:from :)的数据中。

那么,这两种方式有什么区别?我该选哪一个?

php服务是PHP7,swift是version4。

httpBody样式示例:

private func read(){
    let url = URL(string: "http://mywebservice.com/index.php")!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    let string = "username=user1&password=password1"
    request.httpBody = string.data(using: .utf8)
    let task = URLSession.shared.dataTask(with: request){ (data, response, error) in
        //do with data from server
    }
    task.resume()
}

数据样式示例:

private func read2(){
    let url = URL(string: "http://mywebservice.com/index.php")!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    let string = "username=user1&password=password1"
    let data = string.data(using: .utf8)!
    let task = URLSession.shared.uploadTask(with: request, from: data){ (data, response, error) in
        //do with data from server
    }
    task.resume()
}

0 个答案:

没有答案