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

问题描述 投票:0回答:1

以下是我的代码:

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()
ios swift http post
1个回答
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()
    }
© www.soinside.com 2019 - 2024. All rights reserved.