gpt4 book ai didi

swift - 将 Alamofire 调用转换为 URLSession

转载 作者:可可西里 更新时间:2023-10-31 23:14:09 24 4
gpt4 key购买 nike

我有一个旧的代码库,我正试图从中迁移出去。网络调用目前使用 Alamofire 4.0,我正在尝试使用 URLSession。我无法弄清楚出了什么问题,这就是我一直在做的事情。我从要发布的路线和参数开始:

// route to user creation
let url = ...

let params = ["user": ["first_name": "John", "last_name": "Appleseed", "email": "john@apple.com", "password": "asdfgh"]]

这是新旧网络调用:

// old network request
Alamofire.request(url, method: .post, parameters: newUser, encoding: JSONEncoding.default).responseJSON { response in
// ...
}

// new code
var request = URLRequest(url: url)
let jsonData = try! JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
request.httpBody = jsonData
request.httpMethod = "POST"
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { return print("error=\(error)") }

if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("status code should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}

let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
}

task.resume()

出于某种原因,我在 URLSession 尝试中收到状态代码 400。 Alamofire 工作正常。

感谢任何建议。

最佳答案

问题是请求未被识别为 JSON 调用。在创建 URLRequest 后编写以下作业:

request.allHTTPHeaderFields = ["Content-Type": "application/json"]

关于swift - 将 Alamofire 调用转换为 URLSession,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40438578/

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