HttpClient库怎么进行form请求

来源:1-2 课程导学

慕设计5218244

2023-11-28

使用HttpClient 库怎么进行form post请求?

写回答

1回答

CrazyCodeBoy

2023-11-29

可以使用http库,用以下代码执行Form Post请求:

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

void sendFormData() async {
  var url = Uri.parse('https://your-api-endpoint.com');
  var response = await http.post(
    url,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    body: {
      'key1': 'value1',
      'key2': 'value2',
      // Add more key-value pairs as needed
    },
  );

  if (response.statusCode == 200) {
    print('Form data sent successfully');
    print('Response: ${response.body}');
  } else {
    print('Error sending form data. Status code: ${response.statusCode}');
    print('Response: ${response.body}');
  }
}
```

请替换`https://your-api-endpoint.com`为实际的API端点,并根据需要添加更多的键值对到`body`中。这个例子中,`headers`中指定了Content-Type为`application/x-www-form-urlencoded`,以确保请求被正确解析为表单数据。
0
0

Flutter高级进阶实战-仿哔哩哔哩-掌握Flutter高阶技能

一次性掌握Flutter高阶技能+商业级复杂项目架构设计与开发方案

1723 学习 · 870 问题

查看课程