我在这里找到了一个有关如何使用 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/