从VBA调用Rest API-“与服务器的连接异常终止". [英] Calling Rest API from VBA - "Connection with the server was terminated abnormally"

查看:62
本文介绍了从VBA调用Rest API-“与服务器的连接异常终止".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Excel VBA还原RESTfull API.我已经在C#中有了一个工作版本:

I am trying to RESTfull API from Excel VBA. I already have a working version in 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.我写道:

Need to port this code to VBA. I wrote:

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版本时,在.send行上出现错误与服务器的连接异常终止"

When I run the VBA version I get an error "Connection with the server was terminated abnormally" on .Send line

由于它可以在C#中运行,因此不能成为防火墙或服务器问题.我该怎么做才能使其正常工作?我搜索了类似的问题,但没有一个适合我的情况.

Since it works in C# it cannot be a firewall or server problems. What can I do to get it working? I have searched for similar questions but none there are applicable to my situation.

推荐答案

您应该能够执行以下操作:

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=")

我认为问题是,您没有定义的URL.api很有可能是SSL,因此您应该对此加以考虑,这也是为什么在输入字符串时要创建 PostData 的原因.您也有很多引号,我认为您正在这样做是为了正确发送它们,我相信这是不对的.上面的应该适合您.

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.

这篇关于从VBA调用Rest API-“与服务器的连接异常终止".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆