Nick
Nick

Reputation: 4493

How to get value from Flutter/Dart Soap web services asmx call?

I am trying to understand how Flutter and Dart uses soap web services asmx. For this I created very basic project and used online soap WebService asmx for test.

Using http://www.dneonline.com/calculator.asmx?op=Add I successfully build my envelope in Flutter.

In test I use the SOAP 1.1 part.

First I failed to run the app but luckily I found the error on "Content-Length: length". So I remove it and all worked very well.

Its a basic calculator (add) functionality. First I don't know how to add integer inside the envelope, so I use static hard coded values.

In response body I found the < AddResult > 9 < / AddResult > line that has the my answer from soap call.

Second thing is (this is my question) I get response body, but I don't know how to get the value from the body.

How to get value from Flutter/Dart Soap web services asmx call?

This is my full Flutter code.

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _firstInteger = 5;
  int _secondInteger = 4;

  var envelope =
      "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"> <soap:Body> <Add xmlns=\"http://tempuri.org/\"> <intA>5</intA> <intB>4</intB></Add></soap:Body></soap:Envelope>";
  var _testValue = "";
  bool _add = true;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _add = true;
  }

  Future _getCalculator() async {
    http.Response response =
        await http.post('http://www.dneonline.com/calculator.asmx',
            headers: {
              "Content-Type": "text/xml; charset=utf-8",
              "SOAPAction": "http://tempuri.org/Add",
              "Host": "www.dneonline.com"
            },
            body: envelope);

    setState(() {
      _testValue = response.body;
      _add = true;
    });
    print(response.body);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
          child: new Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          _add == true
              ? new Text(
                  "Answer: $_testValue",
                  style: new TextStyle(
                      fontSize: 18.0,
                      fontWeight: FontWeight.bold,
                      color: Colors.red[800]),
                )
              : new CircularProgressIndicator(),
          new RaisedButton(
            onPressed: () {
              setState(() {
                _add = false;
              });
              _getCalculator();
            },
            child: new Text("Calculate"),
          )
        ],
      )),
    );
  }
}

And this is the response.body output:

I/flutter ( 6414): <?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><AddResponse xmlns="http://tempuri.org/"><AddResult>9</AddResult></AddResponse></soap:Body></soap:Envelope>

Upvotes: 0

Views: 6798

Answers (1)

Nick
Nick

Reputation: 4493

Full working code is here:

From Flutter call soap web services asmx and parse it with dart xml. :)

Hope we can get some Dart xml envelope converter so we don't have to create each envelope manually.

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:xml/xml.dart' as xml;


void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _firstInteger = 5;
  int _secondInteger = 4;

  var envelope =
      "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"> <soap:Body> <Add xmlns=\"http://tempuri.org/\"> <intA>5</intA> <intB>4</intB></Add></soap:Body></soap:Envelope>";
  var _testValue = "";
  bool _add = true;

  List<dynamic> itemsList = List();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _add = true;
  }

  Future _getCalculator() async {
    http.Response response =
        await http.post('http://www.dneonline.com/calculator.asmx',
            headers: {
              "Content-Type": "text/xml; charset=utf-8",
              "SOAPAction": "http://tempuri.org/Add",
              "Host": "www.dneonline.com"
            },
            body: envelope);
    var _response = response.body;
    await _parsing(_response);
  }


  Future _parsing(var _response) async {
    var _document = xml.parse(_response);
    Iterable<xml.XmlElement> items = _document.findAllElements('AddResponse');
    items.map((xml.XmlElement item) {
      var _addResult = _getValue(item.findElements("AddResult"));
      itemsList.add(_addResult);
    }).toList();

    print("itemsList: $itemsList");

    setState(() {
      _testValue = itemsList[0].toString();
      _add = true;
    });

  }


  _getValue(Iterable<xml.XmlElement>  items) {
    var textValue;
    items.map((xml.XmlElement node) {
      textValue = node.text;
    }).toList();
    return textValue;
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
          child: new Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          _add == true
              ? new Text(
                  "Answer: $_testValue",
                  style: new TextStyle(
                      fontSize: 18.0,
                      fontWeight: FontWeight.bold,
                      color: Colors.red[800]),
                )
              : new CircularProgressIndicator(),
          new RaisedButton(
            onPressed: () {
              setState(() {
                _add = false;
              });
              _getCalculator();
            },
            child: new Text("Calculate"),
          )
        ],
      )),
    );
  }
}

Upvotes: 4

Related Questions