gpt4 book ai didi

使用 URLSession 进行 Swift API 调用会出现 504 错误

转载 作者:行者123 更新时间:2023-11-30 10:52:16 24 4
gpt4 key购买 nike

我有一个带有 oauth 的 API 调用,我在 postman 中使用正确的授权 token 进行了测试。我在 postman 中得到了正确的响应。但是当我在 Swift 中尝试同样的事情时,我收到 504 错误。

我已经正确检查了每个参数和标题,一切看起来都与 postman 相同。不知道为什么同样的事情在 postman 中工作并在 swift 中给出 504 错误。可能是什么问题?

var params = [String : String]()
params["Id"] = Id;

var headers = [String : String]()
headers["api-key"] = "XXXXXX"
headers["Authorization"] = "Bearer XXX"

do{
var request = URLRequest(url: URL(string: getURL())!)
request.allHTTPHeaderFields = headers
request.httpBody = try JSONSerialization.data(withJSONObject: params , options: [])
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
let httpResponse = response as! HTTPURLResponse
print(httpResponse)
}
task.resume()
}catch{
}

最佳答案

使用 GET 请求时,请求没有正文。一切都在 URL 上。

此外,您确定在 Postman 中仅使用这两个 header 吗?

看看这样的东西是否适合您:

var params: Parameters = Parameters()
params.updateValue(Id, forKey: "Id")

var components = URLComponents(string: getURL())!
components.queryItems = params.map { (key, value) in
URLQueryItem(name: key, value: value)
}
components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")
let request = URLRequest(url: components.url!)
request.setValue("XXXXXX", forHTTPHeaderField: "api-key")
request.setValue("Bearer XXX", forHTTPHeaderField: "Authorization")
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
return
}

if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}

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

关于使用 URLSession 进行 Swift API 调用会出现 504 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54331611/

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