flutterdarthttpopencart

How to send http request in flutter


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.


Solution

  • 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
    

    You can then use http.post() method to send an HTTP request.

    NB: the only required function field is the URL, and must be provided as first parameter, while the others are not strictly needed. Also notice that all the parameters of the HTTP request are provided inside the body, since it's a POST request.

    Example function:

    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'),
            // NB: you don't need to fill headers field
            headers: {
                'Content-Type': 'application/json' // 'application/x-www-form-urlencoded' or whatever you need
            },
            body: {
                'api_token': '768ef1810185cd6562478f61d2',
                'product_id': '100',
                'quantity': '1',
            },
        );
    
        if (response.statusCode == 200) {
            return response.body;
        } else {
            return "Error ${response.statusCode}: ${response.body}";
        }
    }