简体   繁体   中英

How to post/send XML data instead of JSON in rest API Flutter?

I would like to send/post data in Rest API with Flutter. But I cannot find any solution on how to send XML file with Flutter.

I need to send this data in post API 
<?xml version="1.0" encoding="UTF-8"?>
<Request StartDate="2020-07-05" EndDate="2020-07-05" ServiceID="0">
</Request>

And my code is given below which I tried with flutter

  Future<HttpClientResponse> _send() async {
  var builder = new xml.XmlBuilder();
  builder.processing('xml', 'version="1.0" encoding="iso-8859-9"');
  builder.element('Request', nest: () {
      
        builder.attribute('StartDate', '2020-06-02');
        builder.attribute('EndDate', '2020-07-02');
        builder.attribute('ServiceID', '0');     

  });
  var bookshelfXml = builder.build();
  String _uriMsj = bookshelfXml.toString();
  String _uri = "https://my_url";

  var _responseOtp = post(_uri, _uriMsj);
  print("_responseOtp: $_responseOtp");
}


//**POST XML:**

Future<String> post(String _uri, String _message) async {
  HttpClient client = new HttpClient();
  HttpClientRequest request = await client.postUrl(Uri.parse(_uri));
  request.write(_message);
  HttpClientResponse response = await request.close(); 
  StringBuffer _buffer = new StringBuffer();
  await for(String a in await response.transform(utf8.decoder)) {
    _buffer.write(a);
  }
  print("_buffer.toString: ${_buffer.toString()}");
  return _buffer.toString();
}

And it returns this response

  _responseOtp: Instance of 'Future<String>'
    I/flutter ( 9755): _buffer.toString: <?xml version="1.0" encoding="UTF-8" 
    standalone="yes"?>
    I/flutter ( 9755): <Response type="service-response">
    I/flutter ( 9755):   <ResponseCode>1020</ResponseCode>
    I/flutter ( 9755):   <ResponseStatus>error</ResponseStatus>
    I/flutter ( 9755):   <ResponseMessage>Requête invalide</ResponseMessage>
    I/flutter ( 9755): </Response>
  • This data works nicely with the postman

You need to call normally.. just change the headers.

'Content-type' : 'text/xml',

Call like this

return await http.post(
        fullUrl, 
        body:data, // data is your normal json data as a string, 
        headers: {
          'Content-type' : 'text/xml',
        }
    );

Make sure to use async and await to get the result correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM