我编写了一个 AppleScript 函数,它采用 API 端点的 URL,并根据是否有对 HTTP“get”的响应返回
true
或 false
:
use AppleScript version "2.4"
use framework "Foundation"
on ping(api_url)
-- Create the request object.
set ca to current application
set url_string to ca's |NSURL|'s URLWithString:api_url
set request to ca's |NSURLRequest|'s requestWithURL:url_string
-- Try to connect to the endpoint.
set responseData to missing value
set status to missing value
set _response to ca's NSHTTPURLResponse's alloc()'s init()
set {_data, _error} to ca's NSURLConnection's sendSynchronousRequest:request ¬
returningResponse:_response |error|:(reference)
if _error is missing value then
-- No error => connected.
return true
else if class of _error is ca's NSURLError then
return false
else
-- I'm unsure this can ever happen, but let's play it safe.
return false
end if
end ping
-- Simple test.
if ping("https://google.com") then
log "yes"
else
log "no"
end if
现在我想添加一个超时参数,这样如果在给定的时间内没有响应,函数就会返回
false
。我一直不知道该怎么做。一些谷歌搜索让我找到了将 timeoutInterval
与 NSURLConnection 或 NSURLRequest 对象一起使用的示例;不幸的是,当我尝试添加它时,我收到有关“未知选择器”的错误。我的问题可能有一个简单的答案,但我只是没有足够的 AppleScript 经验(要完成这么多工作已经够难的了!)。
如何给这个函数添加超时参数?
更新2024-01-26:我尝试添加超时的方法是将第15-16行更改为:
set {_data, _error} to ca's NSURLConnection's sendSynchronousRequest:request ¬
timeoutInterval:5 returningResponse:_response |error|:(reference)
我也尝试过:
set {_data, _error} to ca's NSURLConnection's sendSynchronousRequest:request ¬
returningResponse:_response |error|:(reference) ¬
cachePolicy:(ca's NSURLRequestReloadIgnoringCacheData) ¬
timeoutInterval:5
错误消息(在Script Debugger中运行时)总是这样:
+[NSURLConnection
sendSynchronousRequest:timeoutInterval:returningResponse:error:]:
unrecognized selector sent to class 0x1eee55848
感谢人们的评论,我能够意识到错误并使事情顺利进行。这里是一个新版本,增加了超时参数,并在其他一些方面进行了改进。关键成分是在 cachePolicy
调用中添加
both
timeoutInterval
和 NSURLRequest
- 尝试仅添加 timeoutInterval
会导致错误:
use AppleScript version "2.5"
use framework "Foundation"
on ping(api_url, max_time)
-- Create the request object.
set ca to current application
set url_string to ca's |NSURL|'s URLWithString:api_url
set ignore_cache to ca's NSURLRequestReloadIgnoringCacheData
set request to ca's NSURLRequest's alloc()'s initWithURL:url_string ¬
cachePolicy:(ignore_cache) timeoutInterval:max_time
-- Try to connect.
set {conn, resp, err} to ca's NSURLConnection's ¬
sendSynchronousRequest:request ¬
returningResponse:(reference) |error|:(reference)
-- No error object => connected.
return (err is missing value)
end ping
这是一个简单的测试脚本:
if ping("https://httpstat.us/504?sleep=3000", 5) then
log "yes (expected)"
else
log "no (unexpected)"
end if
if ping("https://httpstat.us/504?sleep=3000", 2) then
log "yes (unexpected)"
else
log "no (expected)"
end if