Home > Net >  How to retrieve/decode json/map from downloaded ByteStream?
How to retrieve/decode json/map from downloaded ByteStream?

Time:01-07

I have a ByteStream downloaded from a Server, namely datas regarding the user. Its in MySql server as

"username":"Neor","totalCoins":"350"

The truncated part of .php file that gives-away this data, is as follows:

$data = $stmt->fetchColumn();
    header($_SERVER["SERVER_PROTOCOL"] . " 200 OK");
    header("Cache-Control: public");
    header("Content-Type: application/octet-stream");
    header("Content-Transfer-Encoding: Binary");
    header("Content-Length:".strlen($data));
    echo $data;

I use ths Flutter code to download the data:

Future<void> downloadData() async {
var url = Uri.parse("https://example.com/mycloud.php");

var request = http.MultipartRequest('POST', url)
  ..fields["user"] = "Dia";

var response = await request.send();
var stream = response.stream; }

On checking if the downloaded ByteStream contains anything, I've used print(stream.length), which prints out as 137. How can I get the information I want from the ByteStream?

(If my question lacks in any way, please let me know.)

CodePudding user response:

There shouldn't be any need to use a multipart request for a simple POST. Instead use the simpler http.post method.

Future<void> downloadData() async {
  final response = await http.post(
    Uri.parse('https://example.com/mycloud.php'),
    body: <String, String>{
      'user': 'Dia',
    },
  );

  final decodedJson = json.decode(response.body);
  // if you want to ensure the character set used, replace this with:
  // json.decode(utf8.decode(response.bodyBytes));
}

If you do stick with the stream way, you have a Stream<List<int>> that you want to turn initially into a List<int>. Use the toList() method on stream for that. Then you have to decode that into characters. JSON is always encoded in utf8, so you could:

json.decode(utf8.decode(await stream.toList()));

(Under the hood, http is basically doing that for you; collecting the stream together and doing the character decoding and presenting that as body.)

CodePudding user response:

First import 'dart:convert' show utf8; String foo = utf8.decode(bytes); Then Map valueMap = json.decode(foo );

  •  Tags:  
  • Related