XMLHTTP Get请求的responseText为空,即使API返回数据(MS Excel VBA)

i7uaboj4  于 2023-05-19  发布在  其他
关注(0)|答案(1)|浏览(210)

我正在使用下面的代码做一个GET请求到我的Google Sheets' apps脚本项目的Web应用URL -

Dim objRequest As Object
Dim strUrl As String
Dim blnAsync As Boolean
Dim strResponse As String
Dim responseData() As String

Set objRequest = CreateObject("MSXML2.XMLHTTP")
strUrl = "https://script.google.com/macros/s/.../exec?data=" & "id" & " | " & "date1" & "&mode=update"
'above URL works in browser
Debug.Print strUrl
blnAsync = True

With objRequest
    .Open "GET", strUrl, blnAsync
    .Send
    While objRequest.readyState <> 4
        DoEvents
    Wend
    Debug.Print .responseText 'empty
    strResponse = .responseText 'empty
    Debug.Print strResponse 'empty
End With

responseData = Split(strResponse, " | ")
Debug.Print UBound(responseData) - LBound(responseData) + 1 'prints 0

当我在浏览器中打开打印的URL时,我看到数据正在返回-

这意味着我的谷歌应用程序脚本Web应用程序正在工作,但VBA代码不是-什么可能出错?为什么VBA代码不从URL中获取返回的数据?我的最终目标只是得到返回的字符串,将其拆分为" | "字符,并获得responseData变量中的值。
我该怎么办?请引导…Thanks!:)

dxxyhpgq

dxxyhpgq1#

不是一个答案本身,但我最近试图拉回一些文字从网站使用各种代码,我发现在互联网上,其中大部分似乎没有工作。这是否是Office 365的一个古怪之处,或者我只是无法让它们工作,我不知道,但最后我最终使用XMLHTTP60调用来返回我想要的数据,这是从CAS号码中拉回微笑。
我使用的代码,你应该能够适应如下:

Public Function getCactusSMILES(ByVal CAS As String) As String
    ' Requires References: Microsoft XML, v6.0; Microsoft HTML Object Library
    
    Dim myRequest As XMLHTTP60: Set myRequest = New XMLHTTP60
    myRequest.Open "GET", "https://cactus.nci.nih.gov/chemical/structure/" + CAS + "/smiles", False
    myRequest.Send
    
    Dim html As New HTMLDocument
    html.body.innerHTML = myRequest.ResponseText
    If Not html Is Nothing Then
        Dim text As String: text = Trim(html.body.innerText)
        If text <> "Page not found (404)" Then getCactusSMILES = text
    End If
    Set myRequest = Nothing
    DoEvents

End Function

Public Function getPubChemSMILES(ByVal CAS As String) As String
    ' Requires References: Microsoft XML, v6.0; Microsoft HTML Object Library
    
    Dim myRequest As XMLHTTP60: Set myRequest = New XMLHTTP60
    myRequest.Open "GET", "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/xref/rn/" + CAS + "/property/isomericsmiles/txt", False
    myRequest.Send
    
    Dim html As New HTMLDocument
    html.body.innerHTML = myRequest.ResponseText
    If Not html Is Nothing Then
        Dim text As String: text = Trim(html.body.innerText)
        If Not InStr(text, "PUGREST.NotFound") > 0 Then getPubChemSMILES = Split(text, " ")(0)
    End If
    Set myRequest = Nothing
    DoEvents

End Function

相关问题