gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:50:44 26 4
gpt4 key购买 nike

以下是我的代码:

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()

最佳答案

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()
}

关于ios - 创建 http post 请求时我得到 0 字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48336073/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com