我正在做一个需要大量API消耗的Swift项目。一切正常,但有时(20人中有1人),我在调用应用程序接口时遇到Code=-1001 "The request timed out."
错误。
我正在使用Alamofire。我附加了调用API的代码。
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = myUrlContents.dataUsingEncoding(NSUTF8StringEncoding)
request.timeoutInterval = 15
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("\(myUrlContents.dataUsingEncoding(NSUTF8StringEncoding)!.length)", forHTTPHeaderField: "Content-Length")
request.setValue("en-US", forHTTPHeaderField: "Content-Language")
Alamofire.request(request)
.validate()
.responseJSON { [weak self] response in
if response.result.isSuccess {
if let result = response.result.value {
print("Result: \(result)")
completion(result: result as! NSDictionary)
}
}
else {
print(response.debugDescription)
}
}
日志是
[Request]: <NSMutableURLRequest: 0x18855620> { URL: http://....... (url)}
[Response]: nil
[Data]: 0 bytes
[Result]: FAILURE: Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSErrorFailingURLStringKey=http://.....(url) NSErrorFailingURLKey=http://.....(url), NSLocalizedDescription=The request timed out., _kCFStreamErrorDomainKey=4, NSUnderlyingError=0x18a08900 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102}}}
[Timeline]: Timeline: { "Request Start Time": 493582123.103, "Initial Response Time": 493582138.254, "Request Completed Time": 493582138.254, "Serialization Completed Time": 493582138.256, "Latency": 15.151 secs, "Request Duration": 15.151 secs, "Serialization Duration": 0.002 secs, "Total Duration": 15.153 secs }
我知道我可以增加超时时间来避免错误。但我想知道它抛出错误的真正原因。我的API返回数据都没有超过2秒的时间。那么为什么它会显示15.151秒的延迟。
我在后台使用LAMP堆栈。任何帮助都将不胜感激。
发布于 2017-03-17 18:20:01
我得到了错误代码=-1001“请求超时。”我试过一些方法。什么都不管用。最后,我发现问题出在我在请求体中发送给服务器的参数中,这些参数的格式是错误的(值是正确的,但类型是错误的)。这就是请求超时的原因,因为服务器无法处理它。如果其他东西对你都不起作用,你可以检查一下。
发布于 2018-10-19 13:26:42
我刚刚遇到了同样的问题。我正在使用GET请求,但事实证明使用是错误的。您必须在GET请求和POST请求中使用nil
https://stackoverflow.com/questions/39086812
复制相似问题