12

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.

3 Answers 3

33

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

6 Comments

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
cant we send this type of array in get method?
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
good example...
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?
|
0

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

Comments

0
    Future<void> createPost() async {
      try {
        final response = await dio.post(
          'https://jsonplaceholder.typicode.com/posts', // Replace with your API endpoint
          data: {
            'title': 'My New Post',
            'body': 'This is the content of my new post.',
            'userId': 1,
          },
        );
        print('Post created successfully: ${response.data}');
      } on DioException catch (e) {
        if (e.response != null) {
          print('Dio error!');
          print('STATUS: ${e.response?.statusCode}');
          print('DATA: ${e.response?.data}');
          print('HEADERS: ${e.response?.headers}');
        } else {
          // Error due to setting up or sending the request
          print('Error sending request: ${e.message}');
        }
      }
    }

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

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.