如何将已弃用的SoapService调用转换为新的UrlFetchApp

时间:2013-07-27 16:19:44

标签: google-apps-script

我找到了一个关于如何使用google驱动程序脚本调用网络服务的示例: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服务吗?

1 个答案:

答案 0 :(得分:9)

事实证明这是一项更多的工作,但经过一天的谷歌搜索并尝试使用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元素上,导致webservice请求失败