skip to Main Content
session.post(
    'http://myopencart.example.com/index.php?route=api/cart/add',
    params={'api_token':'768ef1810185cd6562478f61d2'},
    data={
        'product_id':'100'
        'quantuty':'1'
    }
)

How to I post this in flutter. In this api there is two type of data to be posted.

I need solution for this I didn’t tried yet.

3

Answers


  1. import 'dart:convert';
    import 'package:http/http.dart' as http;
    
    
    final response = await http.post(
    Uri.parse('http://myopencart.example.com/index.php?route=api/cart/add'),
    body: {
      'api_token': '768ef1810185cd6562478f61d2',
      'product_id': '100',
      'quantity': '1', // Corrected the typo in 'quantity'
     },
     );
    
     if (response.statusCode == 200) {
    // Request was successful, you can handle the response here
    print('Response: ${response.body}');
    } else {
    // Request failed
    print('Failed with status code: ${response.statusCode}');
    }
    
    Login or Signup to reply.
  2. To send HTTP requests in Flutter you can use one of the many packages available. Some examples:

    Example with http package

    You first need to add the package to the dependencies:

    flutter pub add http
    

    Then you could write a function the be called for example when you press a button:

    import 'package:http/http.dart' as http;
    import 'dart:convert';
    
    Future<String> sendPOST() async {
        final response = await http.post(
            Uri.parse('http://myopencart.example.com/index.php?route=api/cart/add'),
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: {
                'api_token': '768ef1810185cd6562478f61d2',
                'product_id': '100',
                'quantity': '1',
            },
        );
    
        if (response.statusCode == 200) {
            return response.body;
        } else {
            return "Error ${response.statusCode}: ${response.body}";
        }
    }
    
    Login or Signup to reply.
  3. First, let’s analyze the api requested parameters:

    Here is how you can perform the request using Http

    var url = Uri.parse(
          'http://myopencart.example.com/index.php?route=api/cart/add');
    
      var data = {
        'product_id': '100',
        'quantity': '1',
      };
    
      // Send the data as a JSON-encoded body
      var response = await http.post(
        url,
        headers: <String, String>{
          'Content-Type': 'application/json; charset=UTF-8',
          'api_token': '768ef1810185cd6562478f61d2',
        },
        body: jsonEncode(data),
      );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search