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

Flutter如何通过HttpServer接收HTML文本输入提交的数据

Dart HttpServer 获取表单提交数据实现方案

核心实现逻辑

  • 启动HttpServer监听指定端口,在listen回调中接收每一个HttpRequest实例
  • 针对GET请求,返回包含文本输入框的HTML表单页面
  • 针对POST请求,读取请求体内容,解析表单字段得到输入框提交的数据

完整代码示例

import 'dart:io';
import 'dart:convert';

void main() async {
  // 绑定本地8080端口
  final server = await HttpServer.bind(InternetAddress.anyIPv4, 8080);
  print('服务已启动,访问 http://localhost:8080 测试');
  
  // 监听请求
  await for (final request in server) {
    try {
      if (request.method == 'GET') {
        // GET请求返回带输入框的表单页面
        request.response
          ..headers.contentType = ContentType.html
          ..write('''
<!DOCTYPE html>
<html>
<body>
  <form method="POST">
    <input type="text" name="inputContent" placeholder="请输入内容" />
    <button type="submit">提交</button>
  </form>
</body>
</html>
          ''');
      } else if (request.method == 'POST') {
        // 读取POST请求体
        final bodyBytes = await request.fold<List<int>>([], (prev, elem) => prev..addAll(elem));
        final bodyStr = utf8.decode(bodyBytes);
        // 解析表单数据
        final formData = Uri.splitQueryString(bodyStr);
        final inputValue = formData['inputContent'] ?? '无输入内容';
        
        // 返回提交结果
        request.response
          ..headers.contentType = ContentType.html
          ..write('''
<!DOCTYPE html>
<html>
<body>
  <p>你提交的内容是:$inputValue</p>
  <a href="/">返回重新提交</a>
</body>
</html>
          ''');
      } else {
        request.response.statusCode = HttpStatus.methodNotAllowed;
        request.response.write('不支持的请求方法');
      }
    } catch (e) {
      request.response.statusCode = HttpStatus.internalServerError;
      request.response.write('服务异常:$e');
    } finally {
      // 必须关闭响应结束请求
      await request.response.close();
    }
  }
}

关键注意点

  • 表单的method必须设置为POST,输入框必须设置name属性,解析时用该属性值作为key获取对应输入内容
  • 读取HttpRequest的请求体时需要先把字节流拼接完整,再转成字符串后用Uri.splitQueryString解析表单格式数据
  • 所有请求处理完成后必须调用response.close(),否则连接会一直挂起

内容的提问来源于stack exchange,提问作者kamil kowalski

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 03:27:05