You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何使用Form Data发送HTTP POST请求?

在Flutter中发送Form Data格式的HTTP POST请求

一、先确认依赖

在项目的pubspec.yaml文件中添加http包依赖,执行flutter pub get完成安装:

dependencies:
  flutter:
    sdk: flutter
  http: ^1.1.0 # 版本号可根据官方最新版本调整

二、普通表单数据(不带文件)

如果接口仅需普通键值对的Form Data(对应Postman中仅添加文本字段的场景),直接用http.post即可,http包会自动将请求头的Content-Type设为application/x-www-form-urlencoded:

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

Future<void> submitForm() async {
  // 替换为你的实际接口地址
  final apiUrl = Uri.parse('https://your-api-endpoint.com/login');
  
  // 表单字段需和后端接口定义完全匹配
  final formFields = {
    'username': 'pluto_web',
    'password': 'your_password',
    'remember_me': 'true'
  };

  try {
    final response = await http.post(
      apiUrl,
      body: formFields,
    );

    if (response.statusCode == 200) {
      print('请求成功,响应内容:${response.body}');
      // 可在此处解析响应JSON数据
    } else {
      print('请求失败,状态码:${response.statusCode},响应:${response.body}');
    }
  } catch (error) {
    print('请求出错:$error');
  }
}

三、带文件的表单数据

如果需要上传文件(对应Postman中Form Data添加文件的场景),需用MultipartRequest构建multipart/form-data格式的请求:

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

Future<void> submitFormWithFile() async {
  final apiUrl = Uri.parse('https://your-api-endpoint.com/upload');
  
  // 创建POST类型的Multipart请求
  final request = http.MultipartRequest('POST', apiUrl);

  // 添加普通文本字段
  request.fields['user_id'] = '123';
  request.fields['description'] = '测试图片上传';

  // 添加本地文件(示例为图片文件)
  final imageFile = File('/storage/emulated/0/Download/test.jpg');
  if (await imageFile.exists()) {
    final multipartFile = await http.MultipartFile.fromPath(
      'avatar', // 后端要求的文件字段名
      imageFile.path,
      contentType: MediaType('image', 'jpg'), // 根据文件类型设置MIME类型
    );
    request.files.add(multipartFile);
  }

  try {
    // 发送请求并获取响应
    final responseStream = await request.send();
    final responseBody = await responseStream.stream.bytesToString();

    if (responseStream.statusCode == 200) {
      print('文件上传成功:$responseBody');
    } else {
      print('上传失败,状态码:${responseStream.statusCode},响应:$responseBody');
    }
  } catch (error) {
    print('上传出错:$error');
  }
}

关键注意事项

  • 必须使用POST方法,GET请求不支持请求体,之前用http.get无法满足需求。
  • 表单字段名要和后端接口定义完全一致,包括大小写。
  • 若后端明确要求multipart/form-data(即使不带文件),也可使用第二种方式,仅添加fields即可。
  • 务必处理网络异常和响应状态码,避免程序崩溃。

内容的提问来源于stack exchange,提问作者Pluto WEB

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 10:30:56