vba - 如何在 VBA 中更改 HttpRequest 的超时?
问题描述
我采用了How do I download a file using VBA (without Internet Explorer)中的代码。除非设备没有应答,否则它工作正常。大约 18 秒后,我将收到错误消息(“-2146697211,系统无法找到指定的资源。”),但在此期间 PC 几乎死机。
由于设备是本地的,我认为 300..500 毫秒的超时就可以了。
Function netDownloadFile(ByVal sURL As String, _
ByVal sLocalFile As String, _
ByRef pCallbackFunc As Long, _
ByRef uTimeoutMillis As Long) As Long
' https://stackoverflow.com/questions/17877389/how-do-i-download-a-file-using-vba-without-internet-explorer
On Error GoTo Err_netDownloadFile
Dim oStream As Object
Dim WinHttpReq As Object
netDownloadFile = 0
Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.SetTimeouts uTimeoutMillis, uTimeoutMillis, uTimeoutMillis, uTimeoutMillis
WinHttpReq.Open "GET", sURL, False
'WinHttpReq.Open "GET", sURL, False, "username", "password"
WinHttpReq.setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" 'disallow caching to get realtime results
WinHttpReq.send
netDownloadFile = WinHttpReq.status
Debug.Print WinHttpReq.getAllResponseHeaders
If WinHttpReq.status = 200 Then
Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1
oStream.Write WinHttpReq.responseBody
oStream.SaveToFile sLocalFile, 2 ' 1 = no overwrite, 2 = overwrite
oStream.Close
GoTo Exit_netDownloadFile
Else
gErrDescription = WinHttpReq.getAllResponseHeaders
End If
Exit_netDownloadFile:
Exit Function
Err_netDownloadFile:
netDownloadFile = Err.Number
gErrDescription = Err.Description
Resume Exit_netDownloadFile
End Function
对此的调用将是:
lngDownloadResult = netDownloadFile("http://192.168.56.42/status/meters", "C:\Temp\Jacuzzi.txt", 0, 300)
我将收到 WinHttpReq.SetTimeouts 的运行时错误:“438 - 对象不支持此属性或方法”。所以这似乎不受 Microsoft.XMLHTTP 支持
我如何需要重新编码(或使用哪个库),以使用短超时?
解决方案
推荐阅读
- python - Python:使用基于正则表达式的逻辑操作选择子集
- flutter - Flutter:在 RichText 中使用可点击的 TextSpan 启用文本选择
- google-apps-script - 如何使我的脚本针对 Google 表格中的多个列?
- php - 在 Laravel 项目中匹配他们彼此喜欢的用户的问题
- javascript - 在 lit-element 中仅用两种方法重构四种方法
- javascript - CSS(?)使用Ctrl + P防止表格打印超过第一页
- sql-server - Understanding CAST/REPLACE Query in SQL Server Query
- javascript - 获取 React 元素的精确副本
- machine-learning - 类型错误:inverse_transform() 缺少 1 个必需的位置参数:'y'
- bash - Bash如何初始化变量并将其值输出到一行中的文件