1

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?

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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,
      ))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.