Home > Back-end >  How to make a http post using form data in flutter
How to make a http post using form data in flutter

Time:10-19

I'm trying to do a http post request and I need to specify the body as form-data, because the server don't take the request as raw or params.

here is the code I tried

** Future getApiResponse(url) async {
    try {
      // fetching data from the url
      final response = await http.get(Uri.parse(url));
      // checking status codes.
      if (response.statusCode == 200 || response.statusCode == 201) {
        responseJson = jsonDecode(response.body);
        // log('$responseJson');
      }
      // debugPrint(response.body.toString());
    } on SocketException {
      throw FetchDataException(message: 'No internet connection');
    }
    return responseJson;
  }
}

but its not working. here is the post man request

enter image description here

its not working on parms. only in body. its because this is in form data I guess. how do I call form data in flutter using HTTP post?

CodePudding user response:

For HTTP you can try this way

final uri = 'yourURL';
var map = new Map<String, dynamic>();
map['device-type'] = 'Android';
map['username'] = 'John';
map['password'] = '123456';

http.Response response = await http.post(
    uri,
    body: map,
);

I have use dio: ^4.0.6 to create FormData and API Calling.

//Create Formdata
formData = FormData.fromMap({
             "username" : "John",
             "password" : "123456", 
             "device-type" : "Android"
        });
   
//API Call
final response = await (_dio.post(
        yourURL,
        data: formData,
        cancelToken: cancelToken ?? _cancelToken,
        options: options,
      ))

CodePudding user response:

First of all you can't send request body with GET request (you have to use POST/PUT etc.) and you can use Map for request body as form data because body in http package only has 3 types: String, List or Map. Try like this:

var formDataMap = Map<String, dynamic>();
formDataMap['username'] = 'username';
formDataMap['password'] = 'password';

final response = await http.post(
    Uri.parse('http/url/of/your/api'),
    body: formDataMap,
);

log(response.body);
  • Related