如果问题标题不正确,我深表歉意-我已经习惯了使用API​​进行PHP 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":"Invalid User Name Or Password","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 的建立。

10-07 20:12
查看更多