在创建http post请求时,我得到0个字节

时间:2018-01-19 07:29:15

标签: ios swift api http post

以下是我的代码:

let session = URLSession.shared
let url = URL.init(string: "http://popularcarsoman.dev.techneek.in/appgateway/endPoint.php")
var urlRequest = URLRequest(url: url!)
urlRequest.httpMethod = "POST"
let parameter = ["action":"FEATUREDCARS"]
do {
   urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameter, options: .prettyPrinted)
}
catch let error {
    print(error.localizedDescription)
}
urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")
let dataTask = session.dataTask(with: url!) { (data, response, error) in
    if (error != nil) {
        let alert = UIAlertController.init(title: "Oops!", message: error?.localizedDescription, preferredStyle: .alert)
        let okAction = UIAlertAction.init(title: "Ok", style: .default, handler: nil)
        alert.addAction(okAction)
        self.present(alert, animated: true, completion: nil)

    }else {
        print("hello")
        print(data ?? Data())
    }
}
dataTask.resume()

1 个答案:

答案 0 :(得分:0)

POST请求正文中存在参数编码问题,目前您正在使用JSONEncoding,但在服务器端,他们正在接受httpBody。在您的请求的完整实现之下:

func callWebService() {
        var config                              :URLSessionConfiguration!
        var urlSession                          :URLSession!

        config = URLSessionConfiguration.default
        urlSession = URLSession(configuration: config)

        let callURL = URL.init(string: "http://popularcarsoman.dev.techneek.in/appgateway/endPoint.php")

        var request = URLRequest.init(url: callURL!)

        request.timeoutInterval = 60.0 // TimeoutInterval in Second
        request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
        request.setValue("application/json", forHTTPHeaderField: "Accept")
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.httpMethod = "POST"
        let param = "action=FEATUREDCARS"
        let data = param.data(using: .utf8, allowLossyConversion: false)
        request.httpBody = data

        let dataTask = urlSession.dataTask(with: request) { (data,response,error) in
            if error != nil{
                return
            }

        }
        dataTask.resume()
    }