如何在REST API Flutter中发布/发送XML数据而不是JSON?

c9x0cxw0  于 2023-06-24  发布在  Flutter
关注(0)|答案(1)|浏览(136)

我想用Flutter在Rest API中发送/发布数据。但是我找不到任何解决方案如何发送XML文件与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>

下面给出了我用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();
}

它返回这个响应

_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>
  • 这个数据与 Postman 很好地配合
af7jpaap

af7jpaap1#

你需要正常打电话。只是改变标题。

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

像这样打电话

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

确保使用async和await来正确地获得结果。

相关问题