Python 在Swift中测量http头请求的响应时间
我试图在Swift中构造一个函数,将http HEAD请求发送到指定的url,并测量来自服务器的响应时间。我不关心解析响应,只关心从服务器获得200。我可以通过请求模块在python中实现这一点:Python 在Swift中测量http头请求的响应时间,python,ios,swift,nsurl,tcp-ip,Python,Ios,Swift,Nsurl,Tcp Ip,我试图在Swift中构造一个函数,将http HEAD请求发送到指定的url,并测量来自服务器的响应时间。我不关心解析响应,只关心从服务器获得200。我可以通过请求模块在python中实现这一点: import requests def get_latency(): r = requests.head("http://example.com") return r.elapsed.total_seconds() 我想我需要使用NSURL来实现这一点,我已经做到了这一点,但还不能找
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)
let url=NSURL(字符串:http://example.com")
let request=NSURLRequest(URL:URL!)
let start=NSDate()
我根据上面的评论写了这个版本。我决定将其设计为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)")
}
}
我今天已经回答了这个问题:这是你需要的吗?嗯,我在操场上试过了,但似乎没有任何作用。。当我调用该类时,在操场中使用异步代码不会发生任何情况,您需要导入XCPlaygroundPage
,并声明XCPlaygroundPage.currentPage.needsIndefiniteExecution=true
:)好的,行了!知道我需要在哪里启动/停止计时器吗?啊,这太令人困惑了。班上的func和isOK的东西真让我讨厌。我所需要做的就是传递一个URL列表,构造并发送head请求,验证200,测量并返回响应时间。你知道我将如何做到这一点吗?