【问题标题】:Calling Rest API from VBA - "Connection with the server was terminated abnormally"从 VBA 调用 Rest API - “与服务器的连接异常终止”
【发布时间】:2018-02-01 17:54:04
【问题描述】:

我正在尝试从 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 版本时,我在 .Send 行收到错误“与服务器的连接异常终止”

由于它在 C# 中工作,它不可能是防火墙或服务器问题。我该怎么做才能让它工作?我搜索了类似的问题,但没有一个适用于我的情况。

【问题讨论】:

  • 你能用 MSXML2.XMLHTTP.6.0 吗?
  • 同样的结果....

标签: c# vba excel winhttprequest


【解决方案1】:

您应该能够做到以下几点:

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。你也有很多引号,我假设你这样做是为了正确发送它们,我相信这是关闭的。以上应该适合你。

【讨论】:

  • 格雷格,感谢您的快速回复。您的解决方案不起作用。首先,我收到一个错误,即 Open 应该在 setRequestHeader 之前。搬家后出现同样的错误:与服务器的连接异常终止
  • @anjulis 如果你下载了 Fiddler,你能看到请求的内容吗?或者在 Postman 中发布数据。是返回成功还是代码也出错了?
  • 我可以在 Postman 或 C# 中运行它。服务器只有 VBA 有问题。
【解决方案2】:

如果您在 Windows 7 或 8 上遇到此问题,则可能与 VBA 使用 SSL 协议发送数据包有关,该数据包被仅接受 TLS 的服务器丢弃。 在这种情况下,您将需要应用 2 步补丁/更新来修复 Windows 7 的此问题,

第 1 步。获取 Microsoft 更新: 下载相关(32位或64位用户Windows版本) Microsoft Security Protocol Update 如果尚未安装,请安装。

第 2 步:下载 Microsoft Easy Fix: 从以下位置下载 Microsoft “Easy Fix” Microsoft Support Article,并执行将 TLS 1.1+ 设置为默认值。

来源:Update to enable TLS 1.1 and TLS 1.2 as default secure protocols in WinHTTP in Windows

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-13
    • 2015-01-30
    相关资源
    最近更新 更多