skip to Main Content

I am not able to get response from http POST in Flutter but URL and data are verified in Postman.

enter image description here

    var map = new Map<String, String>();
    final url = Uri.parse(globals.ServerDomain + '/login');
    Map<String, String> requestBody = <String, String>{
      'username': '80889099',
      'password': '123456789abcde'
    };
    var request = http.MultipartRequest('POST', url)
      ..fields.addAll(requestBody);
    var response = await request.send();
    final respStr = await response.stream.bytesToString();
    print(respStr);

no result returned.

2

Answers


  1. Flutter has this great package called Dio to handle all sort of http requests. It’s very easy to do what you want with it, you are using form data so this is what you should use. For more details check this https://pub.dev/packages/dio#sending-formdata

    Example code:

    final formData = FormData.fromMap(
    {'username': '80889099',
      'password': "123456789abcde",
    });
    final response = await dio.post('${globals.ServerDomain}/login', data: formData);
    
    Login or Signup to reply.
  2. Looks like Its big project changing the package is not a good option try adding request header

    'Content-Type': 'multipart/form-data'

    example code :

    Map<String, String> headers= <String,String>{
         'Authorization':'Basic ${base64Encode(utf8.encode('user:password'))}',//your any other header
         'Content-Type': 'multipart/form-data'
      };
    
    var map = new Map<String, String>();
        final url = Uri.parse(globals.ServerDomain + '/login');
        Map<String, String> requestBody = <String, String>{
          'username': '80889099',
          'password': '123456789abcde'
        };
        var request = http.MultipartRequest('POST', URL)
          ..headers.addAll(headers)
          ..fields.addAll(requestBody);
        var response = await request.send();
        final respStr = await response.stream.bytesToString();
        print(respStr);
    

    Additionally check if internet permission is given (may not be the cause just info)

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