9

I am trying to post a request to api with an object as"

var params =  {
    "item": "itemx",
    "options": [1,2,3],
    };
    print(params);
    try {
      Response response = await _dio.post(getAddToCartURL,
          queryParameters: params,
          options: Options(headers: {
            HttpHeaders.contentTypeHeader: "application/json",
          }));

    } catch (error, stackTrace) {
      print("Exception occurred: $error  stackTrace: $stackTrace");
      return false;
    }

Dio sends the object as :

POST /api/add-to-cart/?item=itemx&options%5B%5D=1&options%5B%5D=2&options%5B%5D=3 

in which the api recognize it as a bad request.

what is wrong that i am doing here? I have even tried the list as [ "1","2","3"], it is the same.

Chosen
  • 847
  • 2
  • 9
  • 21

2 Answers2

28

It all depends on how the API expects it. I would suggest trying to encode it as JSON.

var params =  {
  "item": "itemx",
  "options": jsonEncode([1,2,3]),
};

But sending complex data in query parameters isn't always that easy. Since you are using POST anyway, maybe send a JSON object as body instead of using query parameters.

var params =  {
  "item": "itemx",
  "options": [1,2,3],
}; 
...
Response response = await _dio.post(getAddToCartURL,
  options: Options(headers: {
    HttpHeaders.contentTypeHeader: "application/json",
  }),
  data: jsonEncode(params),
);
dumazy
  • 13,857
  • 12
  • 66
  • 113
  • 1
    thanks for the hint, it actually worked. I thought sending params as an object is enough but as i tried sending authentication params to the same api. Thanks – Chosen May 02 '20 at 02:02
  • cant we send this type of array in get method? – Prabudda Fernando Apr 15 '21 at 20:29
  • GET requests don't have a body and the data has to be put in URL parameters. In general that can be tricky, but it's definitely possible. The first code snippet suggests a way of using GET, the second snippet is for using POST which would generally be the better option but you need to change this on server side as well – dumazy Apr 16 '21 at 08:03
  • good example... – Rahul Kushwaha Mar 29 '22 at 07:06
  • Hi there, I tried this sample code in dio^4.0.6, but I couldn't receive data in my server. Other way I tried @AmirahmadAdibi 's answer and it works. Is this caused by `dio` version? – Kurt Sep 22 '22 at 05:23
  • That would be rather unlikely. I assume your API might be expecting form data instead of json – dumazy Sep 22 '22 at 05:55
1

another example for any one might be helpful , posting fomr data

            var formData = FormData.fromMap({
              'data': json.encode(
                  {'salt': salt, 'placeholder': 'palceholder', 
                  'method_name': 'app_details'})
            });

            var response = await dio.post(
              BaseUrl,
              data: formData,
            );

the final result of your request is this

enter image description here

AmirahmadAdibi
  • 358
  • 3
  • 9