gpt4 book ai didi

进行 URLRequest 时 Swift 随机 400 错误

转载 作者:搜寻专家 更新时间:2023-11-01 07:02:06 24 4
gpt4 key购买 nike

我正在尝试与 API 交互。该服务通常工作并返回 200 响应,但偶尔会响应 400 错误并且调试描述中只有空白 header 。我做了一个递归函数来尝试传递相同的请求,即使我发出相同的请求,我也会在 1-3 次尝试中得到 200 个响应。我已通过 Postman 和 PHP 发出请求,但在与 API 交互时从未遇到过此问题。仅在 Swift 中发出请求时。

    func process(table: String, path: String, objectId: String? = nil, pendingWriteId: String? = nil, method: ApiMethod, processData: [String: Any] = [:], filter: [String: Any] = [:], initializing: Bool = false, remove: Bool = false, completion: @escaping (Error?, JSON) -> Void) {
var timestamp: Int = Int(Date().timeIntervalSince1970)

let session = URLSession.shared
let url : String = "\(apiURL)\(path)"

var params: [String:Any] = [:]

if method != .GET {
params["data"] = processData
params["filter"] = filter
params["timestamp"] = timestamp
}

if method == .DELETE {
params["remove"] = remove
}

let request = NSMutableURLRequest(url: NSURL(string: url)! as URL)
request.httpMethod = method.rawValue

if let token = auth.authToken {
request.setValue(token, forHTTPHeaderField: "token")
}

print(url)
self.sendRequest(session: session, request: request, params: params, pendingWriteId: pendingWriteId, initializing: initializing) { (error, json) in
completion(error, json)
return
}
}

func sendRequest(session: URLSession, request: NSMutableURLRequest, params: [String:Any], pendingWriteId: String?, initializing: Bool, completion: @escaping (Error?, JSON) -> Void) {
do{
request.httpBody = try JSONSerialization.data(withJSONObject: params, options: [JSONSerialization.WritingOptions.prettyPrinted])

_ = session.dataTask(with: request as URLRequest as URLRequest, completionHandler: {(data, response, error) in
DispatchQueue.main.async {
if let response = response {
let nsHTTPResponse = response as! HTTPURLResponse
let statusCode = nsHTTPResponse.statusCode
if statusCode == 200 {
if let d = data {
do {
let json = try JSON(data: d)
print(json)
completion(error, json)
return
} catch {
completion(error, JSON())
return
}
}
} else {
print ("\(request.url) status code = \(statusCode)")
print(nsHTTPResponse.description)
self.sendRequest(session: session, request: request, params: params, pendingWriteId: pendingWriteId, initializing: initializing) { (error, json) in
completion(error, json)
return
}
}
} else {
completion(error, JSON())
return
}
}
}).resume()
}catch _ {
print ("Oops something happened")
completion(ApiError.willNotResolve, JSON())
return
}
}

最佳答案

经过将近一天的尝试解决这个问题后,我在发布问题后的几分钟内解决了这个问题。问题是我试图对空参数集进行 JSON 编码。我变了

request.httpBody = try JSONSerialization.data(withJSONObject: params, options: [JSONSerialization.WritingOptions.prettyPrinted])

if params.count > 0 {
request.httpBody = try JSONSerialization.data(withJSONObject: params, options: [JSONSerialization.WritingOptions.prettyPrinted])
}

现在它按预期工作了

关于进行 URLRequest 时 Swift 随机 400 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50556873/

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