Skip to Content
Author's profile photo Navya Krishna

Consuming Web service in SAPUI5

This is a useful blog for beginners in ui5. This shows an example to consume the webservice in ui5 application. There are different ways in which this can be achieved. I have shown 2 methods in this blog. In both the methods, the input xml to the webservice is posted and the response is taken.

  • Parsing the xml response received from the webservice

var textArea = new sap.ui.commons.TextArea({
                     id : "textArea1"
});
var request = "<Your input xml to the webservice>”;
                    var response = "";
          $.ajax({
                 url : "Your webservice wsdl url",
                 type : "POST",
                 data : request,
                 dataType : "text",
                 contentType : "text/xml; charset=\"utf-8\"",
                 success : function(data, textStatus, jqXHR) {
                        response = data;
                 },
                 error: function(xhr, status)
                 {
                        console.log("ERROR");     
                 },
                 complete : function(xhr,status) {
                        uicontrols();
                 }
          });
                           function uicontrols(){
                     parser=new DOMParser();
                     xmlDoc=parser.parseFromString(response,"text/xml");
                                         var returnVal = xmlDoc.getElementsByTagName("The tag from response xml which you want")              [0].childNodes[0].nodeValue;
                     textArea.setValue(returnVal); //set the value to textArea
          }
  • Using XML model


var request = "<Your input xml to the webservice>”;
                            var response = "";
              $.ajax({
                     url : "Your webservice wsdl url",
                     type : "POST",
                     data : request,
                     dataType : "text",
                     contentType : "text/xml; charset=\"utf-8\"",
                     success : function(data, textStatus, jqXHR) {
                           response = data;
                     },
                     error: function(xhr, status)
                     {
                           console.log("ERROR");     
                     },
                     complete : function(xhr,status) {
                           uicontrols();
                     }
              });
var oModel = new sap.ui.model.xml.XMLModel(); 
                           function uicontrols(){
                     oModel.setXML(response);
}
var oTable = new sap.ui.table.Table({
                     id: "table1"
});
             oTable.addColumn( 
                                          new sap.ui.table.Column({       
                                  label: new sap.ui.commons.Label({text: "Label1"}),       
template: new sap.ui.commons.TextField().bindProperty("value", "Tag1/text()") 
})
              );
              oTable.addColumn( 
                                          new sap.ui.table.Column({       
                                  label: new sap.ui.commons.Label({text: "Label2"}),       
template: new sap.ui.commons.TextField().bindProperty("value", "Tag2/text()") 
})
);
             oTable.setModel(oModel);  
             oTable.bindRows({path: "/the main XML tag under which Tag1 and Tag2 are present/"});


Thank you,

Navya

Assigned tags

      12 Comments
      You must be Logged on to comment or reply to a post.
      Author's profile photo Navya Krishna
      Navya Krishna
      Blog Post Author

      Hi Abhinav,

      Please have a look at this thread. It might help you.

      how to consume OData service in sapui5

      If you want anything else in specific then let me know in detail, will try that out.

      Thank you,

      Navya

      Author's profile photo Former Member
      Former Member

      Hi Navya,

      Nice post you have shared, I followed same and trying to get response of my webservice in UI5 view but it showing me error

      ParseError.PNG

      I have created JS view in my ui5 application and there i have writte below code

      function(oController) {

      var request = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:ValidateuserwebserviceVi">'

      +'<soapenv:Header/><soapenv:Body>'

      +'<urn:Validateuser><urn:Uname>X1801</urn:Uname>'

      +'<urn:Password>asdf@123</urn:Password>'

      +'</urn:Validateuser>'

      +'</soapenv:Body></soapenv:Envelope>';

      var response = "";

      $.ajax({

      url : 'https://10.189.7.13:50101/Validateuserwebservice/ConfigValidate?wsdl',

      type : 'POST',

      dataType  : 'xml'

      data : request,

      contentType : 'text/xml; charset=\"utf-8\"',

      success : function(data, textStatus, jqXHR) {

          

      response = data;

      console.log("data"+data);

      }

      error : function(){

      console:log('ERROR');

      }

      complete : function(xhr,status) { 

      uicontrols();

      }

      });

      var oModel = new sap.ui.model.xml.XMLModel();             

      function uicontrols(){ 

      var oModel = new sap.ui.model.xml.XMLModel();

      var oModel =  sap.ui.model.xml.XMLModel();

      oModel.setXML(response);

      alert("GETXML>>>>"+oModel.getXML());

      var oPage1=new sap.m.Page({

      title : "Test Service"

      });

      return oPage1;

      }}

      );

      Here when i check alert("GETXML>>>>" value it is showing error in parasing .I am using my own webservice which have request

      <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:ValidateuserwebserviceVi">

         <soapenv:Header/>

         <soapenv:Body>

            <urn:Validateuser>

               <urn:Uname>X1801</urn:Uname>

               <urn:Password>asdf@123</urn:Password>

            </urn:Validateuser>

         </soapenv:Body>

      </soapenv:Envelope>

      and on running it on soap ui it showing response

      <SOAP-ENV:Envelope xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

         <SOAP-ENV:Body xmlns:rpl="urn:ValidateuserwebserviceVi">

            <rpl:ValidateuserResponse xmlns:rn0="java:sap/standard" xmlns:rn1="http://schemas.xmlsoap.org/soap/encoding/">

               <rpl:Response>User verified.</rpl:Response>

            </rpl:ValidateuserResponse>

         </SOAP-ENV:Body>

      </SOAP-ENV:Envelope>

      Urgent help needed as without this response i can not possible to proceed with.Please help me step by step process if i am missing some thing or if some demo project avaialble please share that.

      Author's profile photo Vishnu Pankajakshan
      Vishnu Pankajakshan

      Hi Navya,

      How tthe ajax is possible if the web-service that i am requesting is cross domain.

      Regards,

      Vishnu

      Author's profile photo vinayak khosla
      vinayak khosla

      Hi Navya,

      i used the first method ,but i m getting this message on console please help me out.Untitled.pngRegards,

      Vinayak

      Author's profile photo Former Member
      Former Member

      Hi Vinayak,

      This is cross domain issue, which is cuased if the requesting website is served from different domain(localhost) and requested resources are served out of different domain (gateway url).quick fix for development could be, opening the chrome with disabled web security.

      Execute following command in command prompt ( Make sure that all the instances of chrome are closed before executing following commands)

      cd C:\Program Files\Google\Chrome\Application (Change this path accordingly)

      chrome --disable-web-security

      Now in opened browser execute the localhost url, app should work fine.

      One more way is to use proxy servelets :

      The information for the same can be found here

      Use a SimpleProxyServlet for Testing to Avoid Cross-domain Requests - UI Development Toolkit for HTML5 (SAPUI5) - SAP Li…

      Regards,

      Vijay.

      Author's profile photo Karthik A
      Karthik A

      Hi,

      Nice try 🙂 ..But I have few queries.

      1. Why you preferred ajax call?

      Already SAP have odata methods to call GW/webservices.

      OData Model have autoupdate properties as well as more features are appended into oDATA models.

      It could be very useful to you if you used odata model instead of ajax call.

      Thanks,

      Karthik A

      Author's profile photo Former Member
      Former Member

      Hi Karthik,

      I Agree with the argument sapui5 odata model is more matured, it not only helps in CRUD operations, also provides nice binding - templating feature which intern takes care of filtering pagination with ease - by just switching on or off few properties of the control.

      How ever above approach could be useful to consume non oData services like SOAP services or simple REST services.

      Regards,

      Vijay.

      Author's profile photo Hieu Nguyen Minh
      Hieu Nguyen Minh

      Hello Karthik,

      Aggree with you, but sometime backend can not provide Odata service for some reason (in my case, they return XS JS service). Hence we need to use ajax call.

      I'm finding how to use ajax call & get over cross-domain policy. If you have ideas on this, please help me out.

      THanks a lot!

      Author's profile photo Karthik A
      Karthik A

      HI Hieu- Thank you for your comments. I really appreciate your effort to bring up this conversation now.

      I badly need your help on XMLHTTPREQUEST for SAP_ML_API. Can you please help me on it???

      While executing below API call from browser I am getting the attached error, if you have idea please share it with us. 🙂

      Code:

      var data = JSON.stringify({
      				"sourceLanguage": "de",
      				"targetLanguages": [
      					"en"
      				],
      				"units": [{
      					"value": "Der Bestellvorgang bricht beim Speichern der Lieferadresse ab."
      				}]
      			});
      
      			var xhr = new XMLHttpRequest();
      			//xhr.withCredentials = true;
      
      			xhr.addEventListener("readystatechange", function() {
      				if (this.readyState === this.DONE) {
      					console.log(this.responseText);
      				}
      			});
      
      			//setting request method
      			xhr.open("POST", "https://sandbox.api.sap.com/ml/translation/translate");
      			//adding request headers
      			xhr.setRequestHeader("Content-Type", "application/json");
      			xhr.setRequestHeader("Accept", "application/json;charset=UTF-8");
      			xhr.setRequestHeader("APIKey", "<GIVEN CODE>");
      			xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
      			xhr.setRequestHeader("Access-Control-Allow-Methods", "GET,  PUT,  POST,  DELETE");
      			xhr.setRequestHeader("Access-Control-Allow-Headers", "origin, content-type, accept, x-requested-with");
      			xhr.setRequestHeader("Access-Control-Max-Age", "3600");
      			//sending request
      			xhr.send(data);

       

      Regards,

      Karthik A

      Author's profile photo Former Member
      Former Member

      Hello Karthik,

      I'm also trying to consume a machine learning API using a UI5 application.

      Were you able to succeed in your effort, if so please provide your insights.

      Thanks,

      Ashwini

       

      Author's profile photo Former Member
      Former Member

      Hello, Navya!
      I developed a small application based in your first example using the SAP WEB IDE.
      Below follows the source code of my XML view (View1):

      <mvc:View xmlns:html="http://www.w3.org/1999/xhtml" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m" controllerName="TestWebService.controller.View1" displayBlock="true">
      <App>
      <pages>
      <Page title="Call WebService from SAPUI5 (Correios Interface)">
      <content>
      <Button text="Call WebService" width="300px" id="__button0" press="callWebService"/>
      <TextArea id="textArea1" rows="10" cols="150" placeholder="Response message" editable="false"/>
      </content>
      </Page>
      </pages>
      </App>
      </mvc:View>

      Below follows the source code of my view controller:

      var requestMessage;
      var responseMessage;
      var endPointWSDL;
      
      sap.ui.define(["sap/ui/core/mvc/Controller"], function(Controller) {
      	"use strict";
      return Controller.extend("TestWebService.controller.View1", {
      		
      onInit: function() {
      requestMessage = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">';
      requestMessage = requestMessage.concat("<soapenv:Header/>");
      requestMessage = requestMessage.concat("<soapenv:Body>");
      requestMessage = requestMessage.concat(" <tem:CalcPrecoPrazo>");
      requestMessage = requestMessage.concat("<tem:nCdEmpresa>49436</tem:nCdEmpresa>");
      requestMessage = requestMessage.concat("<tem:sDsSenha></tem:sDsSenha>");
      requestMessage = requestMessage.concat("<tem:nCdServico>40010</tem:nCdServico>");
      requestMessage = requestMessage.concat("<tem:sCepOrigem>05422030</tem:sCepOrigem>");
      requestMessage = requestMessage.concat("<tem:sCepDestino>06026090</tem:sCepDestino>");
      requestMessage = requestMessage.concat("<tem:nVlPeso>1</tem:nVlPeso>");
      requestMessage = requestMessage.concat("<tem:nCdFormato>3</tem:nCdFormato>");
      requestMessage = requestMessage.concat("<tem:nVlComprimento>20.00</tem:nVlComprimento>");
      requestMessage = requestMessage.concat("<tem:nVlAltura>0</tem:nVlAltura>");
      requestMessage = requestMessage.concat("<tem:nVlLargura>12.00</tem:nVlLargura>");
      requestMessage = requestMessage.concat("<tem:nVlDiametro>0</tem:nVlDiametro>");
      requestMessage = requestMessage.concat("<tem:sCdMaoPropria>N</tem:sCdMaoPropria>");
      requestMessage = requestMessage.concat("<tem:nVlValorDeclarado>0</tem:nVlValorDeclarado>");
      requestMessage = requestMessage.concat("<tem:sCdAvisoRecebimento>N</tem:sCdAvisoRecebimento>");
      requestMessage = requestMessage.concat("</tem:CalcPrecoPrazo>");
      requestMessage = requestMessage.concat("</soapenv:Body>");
      requestMessage = requestMessage.concat("</soapenv:Envelope>");
      responseMessage = "";
      endPointWSDL = "http://ws.correios.com.br/calculador/CalcPrecoPrazo.asmx?WSDL";
      },
      		
      //on press button:
      callWebService: function() {
      			
      var textArea = new sap.ui.commons.TextArea({ id : "textArea1" });
      			
      function uicontrols(){
      var parser = new DOMParser();
      var xmlDoc = parser.parseFromString(responseMessage,"text/xml");
      var returnVal = xmlDoc.getElementsByTagName("Servicos")[0].childNodes[0].nodeValue;
      textArea.setValue(returnVal); //set the value to textArea
      }
                
      $.ajax({
      url : endPointWSDL,
      type : "POST",
      data : requestMessage,
      dataType : "text",
      contentType : "text/xml; charset=\"utf-8\"",
      success : function(data, textStatus, jqXHR) {
      responseMessage = data;
      },
      error: function(xhr, status)
      {
      sap.ui.commons.MessageBox.alert("Error to consume WebService");
      },
      complete : function(xhr,status) {
      uicontrols();
      }
      });
                
      }
      		
      });
      });

      Could you tell me what I'm doing wrong, please?
      Thank you very much!
      Rubens

      Author's profile photo Raghavendra H K
      Raghavendra H K

      Hi Navya,

      For consuming oData services I can create destination and I could able to get the data in component.js,

      But in my workflow I am using XSOData ....In my  scenario I need to post the data in component.js for Hana database ....Is it possible to call hana services in component.js?

      Thanks & Regards,

      Raghavendra H K