我正在尝试从Excel VBA中使用RESTfull API。 我已经在C#中使用了一个工作版本:
//Request Auth Token
var client = new RestClient("https://api.xxx.com/exp/oauth2/v1/access_token_cors");
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", "response_type=token&grant_type=client_credentials&client_id=1234&client_secret=1234&scope=", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
需要将此代码移植到VBA。我写道:
Set MyRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
MyRequest.Open "POST", "https://api.xxx.com/exp/oauth2/v1/access_token_cors", False
MyRequest.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
PostData = """application/x-www-form-urlencoded"", ""response_type=token&grant_type=client_credentials&client_id=1234&client_secret=1234&scope="""
MyRequest.send (PostData)
当我运行VBA版本时,我收到错误“与服务器的连接异常终止”。发送行
因为它在C#中工作,所以它不能是防火墙或服务器问题。我能做些什么才能让它发挥作用?我搜索过类似的问题,但没有一个适用于我的情况。
答案 0 :(得分:1)
You should be able to do the following:
Set request = CreateObject("WinHttp.WinHttpRequest.5.1")
request.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
request.Open "POST", URL, False 'Your missing the actual url
request.Option(4) 'Ignore SSL Errors.
request.Option(12) 'Allow redirect to SSL
request.send("response_type=token&grant_type=client_credentials&client_id=1234&client_secret=1234&scope=")
I assume the issue is, you don't have a defined URL. More than likely the api could be SSL, so you should account for that, also why create a PostData
when you can input the string. You also have a lot of quotation marks, I assume you're doing that to correctly send them, I believe that is off. The above should work for you.
答案 1 :(得分:0)
如果您在Windows 7或8上遇到此问题,则可能与VBA使用SSL协议发送数据包有关,该数据包仅由接受TLS的服务器丢弃。 在这种情况下,您将需要进行两步修补/更新才能修复Windows 7上的问题,
步骤1。获取Microsoft Update: 下载相关的(32位或64位用户的Windows版本) Microsoft Security Protocol Update并安装(如果尚未安装)。
步骤2。下载Microsoft Easy Fix: 从以下位置下载Microsoft“轻松修复” Microsoft Support Article,然后执行以将TLS 1.1+设置为默认值。
来源:Update to enable TLS 1.1 and TLS 1.2 as default secure protocols in WinHTTP in Windows