如何在flutter中发送http请求

问题描述 投票:0回答:2
session.post(
    'http://myopencart.example.com/index.php?route=api/cart/add',
    params={'api_token':'768ef1810185cd6562478f61d2'},
    data={
        'product_id':'100'
        'quantuty':'1'
    }
)

如何在 flutter 中发布此内容。在此 api 中,有两种类型的数据要发布。

我需要解决这个问题,我还没有尝试过。

flutter api dart http opencart
2个回答
1
投票

要在 Flutter 中发送 HTTP 请求,您可以使用许多可用的包之一,例如:

带有
http
包的示例

您首先需要将包添加到依赖项中

flutter pub add http

然后你可以编写一个函数,例如当你按下按钮时被调用:

import 'package:http/http.dart' as http;

void 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) {
        // OK
    } else {
        // Error
    }
}

0
投票
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}');
}
© www.soinside.com 2019 - 2024. All rights reserved.