excel - 在 VBA 中使用 xmlHttp 建立 API session

标签 excel vba session xmlhttprequest

如果我的问题标题不正确,我深表歉意 - 我已经习惯了 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/

相关文章:

c# - COMException 故障

c# - 从 C# 打开 Excel ODBC 连接

c# - 使用 EPPlus 在 Excel 中插入一行

ruby - 浏览器之间共享的 Sinatra Session 数据

excel - 包含特定文本的单元格计数

vba - 将 now() 转换为 MS Access VBA 中的特定格式

vba - 将集合和对象写入磁盘并稍后重新导入的最佳策略是什么?

excel - 如何使用 vba 更新 powerpoint 2010 中嵌入的 Excel 链接

wcf - 以编程方式将自定义 WCF header 添加到终结点以实现可靠 session

amazon-web-services - 何时显式使用 boto3 session