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

标签 swift urlsession http-status-code-504

我有一个带有 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/

相关文章:

node.js - 无法加载资源: the server responded with a status of 504 (Timeout while reading response from Server) Node. js,Nginx

ios - 如何在 View Controller 中使用更多菜单 Controller

swift - SpriteKit SKSprite节点

swift - 无法推断通用参数 'S' + 对成员 'count' 的引用不明确

Swift 泛型与任何泛型

http - HTTP 408 和 504 错误有什么区别?

Git 错误 : The requested URL returned error: 504 Gateway Timeout while accessing http://

ios - Swift 结合 URLSession 使用 2x Publishers 检索数据集/照片

swift - URLSession 完成器的单元测试包装器

authentication - 如何在 urlsession 中验证代理?