如果我的问题标题不正确,我深表歉意 - 我已经习惯了 PHP 与 API session 的想法。
我正在尝试使用以下代码在 VBA 中完成相同的任务:
'Login
strLogin = "https://URL.COM/authenticateUser?login=username&apiKey=password"
Set xmlHttp = CreateObject("MSXML2.ServerXMLHTTP.6.0")
xmlHttp.Open "GET", strLogin
xmlHttp.setRequestHeader "Content-Type", "text/xml"
xmlHttp.send
'Save the response to a string
strReturn = xmlHttp.responseText
'Open URL and get JSON data
strUrl = "https://URL.COM/Search/search?searchTerm=" & Keyword & "&mode=beginwith"
Set xmlHttp = CreateObject("MSXML2.ServerXMLHTTP.6.0")
xmlHttp.Open "GET", strUrl
xmlHttp.setRequestHeader "Content-Type", "text/xml"
xmlHttp.send
'Save the response to a string
strReturn = xmlHttp.responseText
Sheets(1).Cells(20, 2).Value = strReturn
使用此 API,我需要先登录,然后才能执行任何将返回数据的调用。
我的问题是我无法确定如何“保持登录状态”以便我的第二个调用正常工作。
登录后,strReturn
会填充以下字符串:
{"Status":{"Code":"2","Message":"Authentication Succeeded","Success":"true"}}
但是,当我使用 strUrl
时,我收到以下消息:
{"Status":{"Code":"1","Message":"用户名或密码无效","Success":"false"}}
我在之前的项目中使用过这段代码,我需要为每个服务器请求提供 API key 和 URL - 所以这显然工作得很好。我不确定如何使用 xmlHttp 实现“建立 session ”的概念。
最佳答案
因此,对于遇到此问题的其他人来说,简单的解决方案是从第二个调用中删除以下行:
Set xmlHttp = CreateObject("MSXML2.ServerXMLHTTP.6.0")
通过不创建新对象,vba 能够保留并使用第一次登录调用时的 cookie。
最终的代码如下所示:
'Login
strLogin = "https://URL.COM/authenticateUser?login=username&apiKey=password"
Set xmlHttp = CreateObject("MSXML2.ServerXMLHTTP.6.0")
xmlHttp.Open "GET", strLogin
xmlHttp.setRequestHeader "Content-Type", "text/xml"
xmlHttp.send
'Save the response to a string
strReturn = xmlHttp.responseText
'Open URL and get JSON data
strUrl = "https://URL.COM/Search/search?searchTerm=" & Keyword & "&mode=beginwith"
xmlHttp.Open "GET", strUrl
xmlHttp.setRequestHeader "Content-Type", "text/xml"
xmlHttp.send
'Save the response to a string
strReturn = xmlHttp.responseText
Sheets(1).Cells(20, 2).Value = strReturn
需要登录的 API 能够保持 session 建立。
关于excel - 在 VBA 中使用 xmlHttp 建立 API session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31434437/