2013-07-27 29 views
6

我發現瞭如何調用web服務與谷歌在此驅動腳本的例子:https://developers.google.com/apps-script/articles/soap_geoip_example如何將已過時SoapService調用轉換爲新的UrlFetchApp

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服務?

+0

用'google-apps-script'代替這個問題而不是'google-drive -sdk'。 –

回答

8

它原來是多了很多的工作,但谷歌搜索,並試圖一整天后,我得到它與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(); 
} 

工作應該probely是塑形與XmlService建立有效載荷的xml ,但是我嘗試了幾個小時,並且無法在Evnelope元素上放置4個xmlns屬性,導致web服務請求失敗

+0

我得到了來自服務器的400響應...因爲它的谷歌,我不知道如何請求實際上,如果我使用getRequest,請求看起來不錯。任何幫助? –

+0

我今天再試一遍,上面的代碼仍然有效,如果你收到400(壞請求),可能是因爲你的xml編譯不正確,考慮轉義雙引號和反斜槓,也可能是目標服務器的決定即使請求是正確的但返回一個錯誤的請求,但有一些他們錯過或不喜歡 – Jarno

+0

感謝您的一個很好的答案!第一個如何使用UrlFetchApp進行Web服務的工作示例,儘管我已經搜索了一下它! –

相關問題