How to send http request in flutter

556 Views Asked by At
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

There are 3 best solutions below

0
mikyll98 On BEST ANSWER

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}";
    }
}
1
Arbaan Qureshi On
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}');
}
0
Loïc Yabili On

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