Bri*_*ell 5 excel session vba excel-vba
如果问题标题不正确,我深表歉意-我已经习惯了使用API进行PHP会话的想法。
我正在尝试通过以下代码在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
Run Code Online (Sandbox Code Playgroud)
使用此API,我需要先登录才能执行任何将返回数据的调用。
我的问题是我无法确定如何“保持登录”,这样我的第二个电话才能正常工作。
登录后,strReturn将使用以下字符串填充:
{"Status":{"Code":"2","Message":"Authentication Succeeded","Success":"true"}}
Run Code Online (Sandbox Code Playgroud)
但是,当我利用时strUrl,会收到以下消息:
{"Status":{"Code":"1","Message":"Invalid User Name Or Password","Success":"false"}}
我在以前的项目中使用了此代码,在这些项目中,我需要向服务器提供每个请求的API密钥以及URL-因此,这显然可以正常工作。我不确定如何使用xmlHttp实现“建立会话”的概念。
因此,对于遇到此问题的其他任何人,简单的解决方案是从第二个调用中删除以下行:
Set xmlHttp = CreateObject("MSXML2.ServerXMLHTTP.6.0")
Run Code Online (Sandbox Code Playgroud)
通过不创建新对象,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
Run Code Online (Sandbox Code Playgroud)
并且需要登录的API能够保持会话建立。