Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an deprecated SoapService call to the new UrlFetchApp

I found an example on how to call a webservice with Google drive scripts here: 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;
}

However this uses the SoapService which is deprecated. the documentation says I should use UrlFetchApp Converting the input xml is easy. But can anyone tell me how to call a webservice with the UrlFetchApp?

like image 675
Jarno Avatar asked Jul 27 '13 16:07

Jarno


1 Answers

It turns out to be a lot more work, but after a day of googling and trying i got it to work with the 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();
}

It should probely be posable to build the payload xml with the XmlService, however i tryed that for a few hours and was unable to put the 4 xmlns attributes on the Evnelope element, wich caused the webservice request to fail

like image 166
Jarno Avatar answered Nov 03 '22 01:11

Jarno