Home > database >  Http Request Flutter didn't have body
Http Request Flutter didn't have body

Time:01-12

I have a project with Flutter. And I want to get data from API. In my other project, I don't have any problem. But in this project, I have a problem. When I debug the process, in HTTP response didn't have body from API.

In class AuthService to get the API.

Future<ResponseCheckNIP> checkNIP({String? nip}) async {
 var url = '$baseUrl/check-nip-new/$nip';
 var header = {
   'Content-Type': 'application/json',
 };
 // var body = jsonEncode({'nip': nip});
 var response = await http.get(Uri.parse(url), headers: header);
 if (response.statusCode == 200) {
   var data = jsonDecode(response.body);
   ResponseCheckNIP responseCheckNIP = ResponseCheckNIP.fromJson(data);
   return responseCheckNIP;
 } else {
   throw Exception('Get NIP Failed');
 }
}

And when I debug it, I get this

enter image description here

as we see, there is no body in there. Am I did something wrong?

CodePudding user response:

If you look closely, the data is actually in the response.bodyBytes.

And Since you cannot directly convert bytes to json with dart, convert bytes to String first then decode the String using jsonDecode.

Below is the modified code.

Future<ResponseCheckNIP> checkNIP({String? nip}) async {
  var url = '$baseUrl/check-nip-new/$nip';
  var header = {
    'Content-Type': 'application/json',
  };
  var response = await http.get(Uri.parse(url), headers: header);
  if (response.statusCode == 200) {
    
    // Get body bytes from response
    final bytes = response.bodyBytes;
    // Convert bytes to String then decode
    final data = jsonDecode(utf8.decode(bytes));

    ResponseCheckNIP responseCheckNIP = ResponseCheckNIP.fromJson(data);
    return responseCheckNIP;
  } else {
    throw Exception('Get NIP Failed');
  }
}

Hope this helps. Thank you.

  • Related