gpt4 book ai didi

ios - 在 swift 3.2 中使用 json 和 header 请求 AFNetworking

转载 作者:行者123 更新时间:2023-11-28 06:10:42 25 4
gpt4 key购买 nike

let header = [
"Content-Type":"application/json",
"X-Source":"iOS",
"Authorization":token]
let strURL = "ValidURL"


let manager = AFHTTPSessionManager()
let serializer = AFHTTPRequestSerializer()
for (_,dict) in header.enumerated() {
serializer.setValue("\(dict.value)", forHTTPHeaderField: "\(dict.key)")
}
manager.requestSerializer = serializer

let req = serializer.request(withMethod: "POST", urlString: strURL, parameters: params, error: nil)
manager.dataTask(with: req as URLRequest) { (response, data, error) in
print(error)
print(response)
print(data)
}
//No response from this method

另外,我试过:

var request = URLRequest(url: URL(string: strURL)!)
request.httpMethod = "POST"
for (_,dict) in header.enumerated() {
request.setValue("\(dict.value)", forHTTPHeaderField: "\(dict.key)")
}
request.httpBody = try! JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
manager.dataTask(with: request) { (response, data, error) in
print(error)
print(response)
print(data)
}

连我都试过了:

manager.post(strURL, parameters: params, progress: nil, success: { (sessionTask, respose) in
if let dict = respose as? Dictionary<String,Any> {
print(dict)
} else {
}
}) { (task, error) in
print(error)
}

//It Give me: failed: bad request (400)

最佳答案

这里有两个问题

  1. 当您使用 dataTask 方法时,您会得到一个任务对象。当您希望发送请求时,您需要对其调用 resume()

  2. 您的错误表明您的 JSON 正文不正确。那是在您的 params 对象中,它可能与服务所期望的不匹配。

关于ios - 在 swift 3.2 中使用 json 和 header 请求 AFNetworking,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46773504/

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