我正在尝试在Swift中构造一个函数,它将http HEAD请求发送到指定的url,并测量服务器的响应时间。我并不关心解析响应,只是说我从服务器获得了200。我可以使用请求模块在python中执行此操作:
import requests
def get_latency():
r = requests.head("http://example.com")
return r.elapsed.total_seconds()
我假设我需要使用NSURL,我已经能够做到这一点,但无法找出实际发送请求的最佳方式......
let url = NSURL (string: "http://example.com")
let request = NSURLRequest(URL: url!)
let started = NSDate()
<<<Send http HEAD request, verify response>>> <- need help here
let interval = NSDate().timeIntervalSinceDate(started)
答案 0 :(得分:0)
我根据以上评论编写了此版本。我决定将其设计为URL类的扩展。我已经使用 Swift 4 测试了此代码。
extension URL {
/** Request the http status of the URL resource by sending a "HEAD" request over the network. A nil response means an error occurred. */
public func requestHTTPStatus(completion: @escaping (_ status: Int?) -> Void) {
// Adapted from https://stackoverflow.com/a/35720670/7488171
var request = URLRequest(url: self)
request.httpMethod = "HEAD"
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let httpResponse = response as? HTTPURLResponse, error == nil {
completion(httpResponse.statusCode)
} else {
completion(nil)
}
}
task.resume()
}
/** Measure the response time in seconds of an http "HEAD" request to the URL resource. A nil response means an error occurred. */
public func responseTime(completion: @escaping (TimeInterval?) -> Void) {
let startTime = DispatchTime.now().uptimeNanoseconds
requestHTTPStatus { (status) in
if status != nil {
let elapsedNanoseconds = DispatchTime.now().uptimeNanoseconds - startTime
completion(TimeInterval(elapsedNanoseconds)/1e9)
}
else {
completion(nil)
}
}
}
}
用法:
let testURL = URL(string: "https://www.example.com")
testURL?.responseTime { (time) in
if let responseTime = time {
print("Response time: \(responseTime)")
}
}