google-apps-script - 如何将已弃用的 SoapService 调用转换为新的 UrlFetchApp

标签 google-apps-script

我在这里找到了一个有关如何使用 Google Drive 脚本调用 Web 服务的示例:https://developers.google.com/apps-script/articles/soap_geoip_example

function determineCountryFromIP(ipAddress) {
    var wsdl = SoapService.wsdl("http://www.webservicex.net/geoipservice.asmx?wsdl");
    var geoService = wsdl.getGeoIPService();

    var param = Xml.element("GetGeoIP", [
              Xml.attribute("xmlns", "http://www.webservicex.net/"),
              Xml.element("IPAddress", [
                ipAddress
              ])
            ]);

    var result = geoService.GetGeoIP(param);
    return result.Envelope.Body.GetGeoIPResponse.GetGeoIPResult.CountryCode.Text;
}

但是,这使用了已弃用的 SoapService。文档说我应该使用 UrlFetchApp 转换输入 xml 很容易。但谁能告诉我如何使用 UrlFetchApp 调用 Web 服务?

最佳答案

事实证明,这需要做更多的工作,但经过一天的谷歌搜索和尝试,我让它与 UrlFetchApp 一起工作。

function UrlFetchAppDetermineCountryFromIP_(ipAddress) {
  var xml =          
     "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
    +"<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
      +"<SOAP-ENV:Body>"
        +"<GetGeoIP xmlns=\"http://www.webservicex.net/\">"
          +"<IPAddress>"+ ipAddress +"</IPAddress>"
        +"</GetGeoIP>"
      +"</SOAP-ENV:Body>"
    +"</SOAP-ENV:Envelope>"

  var options =
  {
    "method" : "post",
    "contentType" : "text/xml",
    "payload" : xml
  };

  var result = UrlFetchApp.fetch("http://www.webservicex.net/geoipservice.asmx?wsdl", options);

  var xmlResult = XmlService.parse(result).getRootElement();
  var soapNamespace = xmlResult.getNamespace("soap");
  var getGeoIPResponse = xmlResult.getChild("Body", soapNamespace).getChildren()[0];
  var getGeoIPResponseNamespace = getGeoIPResponse.getNamespace();

  return getGeoIPResponse
    .getChild("GetGeoIPResult", getGeoIPResponseNamespace)
    .getChild("CountryCode", getGeoIPResponseNamespace)
    .getText();
}

应该可以使用 XmlService 构建有效负载 xml ,但是我尝试了几个小时,但无法将 4 个 xmlns 属性放在 Evnelope 元素上,这导致 Web 服务请求失败

关于google-apps-script - 如何将已弃用的 SoapService 调用转换为新的 UrlFetchApp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17899937/

相关文章:

google-apps-script - 如何获取当前临时 "anonymous"活跃用户 key ?

javascript - 没有 "var = "的变量可以吗?

javascript - 在 Google Apps 脚本自定义函数中访问和抓取逗号分隔的 UTF-8 文本网页

javascript - 通过谷歌应用程序脚本向不和谐发送消息

google-apps-script - 谷歌电子表格 : Sum of all bold cells

google-apps-script - 表单提交触发器 - 来自 Google Docs 表单的脚本结果

javascript - 通过一次表单提交将多个文件上传到一个文件夹中

google-apps-script - 正确安全地登录(登录)部署为网络应用程序的 Google Apps 脚本项目

google-apps-script - 谷歌应用程序脚本 UrlFetchApp.fetch 限制?

javascript - Google 应用程序脚本 - 将一些功能移动到单独的文件中