vba Excel中通过VBA访问API

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44677873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 12:45:39  来源:igfitidea点击:

Access API through VBA in Excel

excelvbaapi

提问by Nico Ditu

I need log in to this API: http://demo-api.primary.com.ar:8081/pbcp/rest/users/login

我需要登录这个 API:http: //demo-api.primary.com.ar: 8081/pbcp/rest/users/login

There is a quickstart guidewith all information, but I never used those instructions and I don't know how perform a macro in Excel to connect and then get market data

有一个包含所有信息的快速入门指南,但我从未使用过这些说明,我不知道如何在 Excel 中执行宏来连接然后获取市场数据

I tried different methods in Excel but I can't make it work. My last attempt was to send through WinHttp.WinHttpRequest.5.1headers like express in cUrl but the errors are systematical.

我在 Excel 中尝试了不同的方法,但无法使其工作。我的最后一次尝试是通过WinHttp.WinHttpRequest.5.1cUrl 中的 express 之类的标头发送,但错误是系统性的。

Here is my code, which is a compilation of different bits of code extracted from the web.

这是我的代码,它是从网络中提取的不同代码位的汇编。

curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{
  "username": "Demo-User",
  "password": "ApiEx@mpl3"
}' 'http://demo-api.primary.com.ar:8081/pbcp/rest/users/login'

My code:

我的代码:

Sub prueba()

Dim oRequest As Object
Set oRequest = CreateObject("WinHttp.WinHttpRequest.5.1")

Dim h1 As String
Dim h2 As String

oRequest.Open "POST", "http://demo-api.primary.com.ar:8081/pbcp/rest/users/login"
oRequest.SetRequestHeader "Content-Type", "application/json", "Accept", "application/json" ''Content-Type: application/json'

Dim s As String
s = Chr(34) & "username" & Chr(34) & ":" & Chr(34) & "Demo-User" & Chr(34) & "," & Chr(34) & "password" & Chr(34) & ":" & Chr(34) & "ApiEx@mpl3" & Chr(34)

oRequest.Send s
MsgBox oRequest.ResponseText
End Sub


'Dim oRequest As Object
'Set oRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
'oRequest.Open "POST", "http://demo-api.primary.com.ar:8081/pbcp/rest/users/login"
'oRequest.SetRequestHeader "Content-Typ", "application/x-www-form-urlencoded"
'oRequest.Send "var1=123&anothervar=test"
'MsgBox oRequest.ResponseText

回答by Alex K.

  1. You need to call SetRequestHeaderfor eachheader and value, you cant combine them
  2. The request is JSON but you omit the {}
  1. 您需要SetRequestHeader每个标头和值调用,您不能将它们组合起来
  2. 请求是 JSON 但您省略了 {}


oRequest.Open "POST", "http://demo-api.primary.com.ar:8081/pbcp/rest/users/login"
oRequest.SetRequestHeader "Content-Type", "application/json"
oRequest.SetRequestHeader "Accept", "application/json"

Dim s As String
s = "{" & Chr(34) & "username" & Chr(34) & ":" & Chr(34) & "Demo-User" & Chr(34) & "," & Chr(34) & "password" & Chr(34) & ":" & Chr(34) & "ApiEx@mpl3" & Chr(34) & "}"