skip to Main Content

I have a button which when clicked, prints out response.

This is how the response is

{
    "status": "success",
    "user": "Worked well"
}

when I test it with postman it works fine, but when I try it from my flutter project, I get this error

I/flutter ( 5147): Response: - Instance of 'Response'
I/flutter ( 5147): FormatException: Unexpected character (at character 1)
I/flutter ( 5147): <!DOCTYPE html>
I/flutter ( 5147): ^

This is my flutter code:

  http.Response response = await http.post(
    Uri.parse(url + 'testMe.php'),
    headers: headers,
    body: body,
  );
  print('response ${response}');
  if (response.body.isNotEmpty) {
    json.decode(json.encode(response.body));
  } else {
    print('Response is empty...');
  }

One thing I noticed is that, sometimes it does not throw the error above in flutter, it works fine and sometimes it throws the error, so I don’t why it happen that way.

Flutter Header

Postman Headerenter image description here

2

Answers


  1. This worked for me:

    Map<String, String> headers = {
     'Content-Type': 'application/json',
     'Charset': 'utf-8',
    };
    
    Login or Signup to reply.
  2. Your api return you a html instead of json, you can do this to avoid getting FormatException:

    http.Response response = await http.post(
      Uri.parse(url + 'testMe.php'),
      headers: headers,
      body: body,
    );
    
    print('response ${response}');
    if (response.statusCode == 200) {
      json.decode(response.body);
    } else {
      print('Response is empty...');
    }
    

    usually when statuscode is 500 or 404 this happened, when you check for status code 200, you can avoid getting this FormatException.

    Also you don’t need to encode the response and decode it again, your response is already encoded in server side, just decode it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search