gpt4 book ai didi

json - 如何在Dart Server中设置request.response的内容类型?

转载 作者:行者123 更新时间:2023-12-03 03:41:46 25 4
gpt4 key购买 nike

我如下图所示设置了镖服务器。我可以从Flutter Mobile应用发送数据,也可以从Dart Server接收数据。

如果请求方法是dart Server中的GET,我将连接到tcp套接字获取一些数据。我需要发送到Flutter应用程序的数据必须为JSON格式。

我尝试将request.response.headers.contentType设置为json,但我不断收到错误消息HttpException:HTTP头不可更改。

代码部分:

var _secureResponse = {};
_secureResponse[“Data”] = "$_returningServerData";
_secureResult = json.encode(_secureResponse);

request.response.headers.contentType = new ContentType("application", "json", charset: "utf-8");
request.response.write(_secureResult);
request.response.close();

错误:
  • 未处理的异常:HttpException:HTTP头不是可变的
  • HttpHeaders._checkMutable(dart:_http / http_headers.dart:447:20)
  • HttpHeaders.contentType =(dart:_http / http_headers.dart:267:5)

  • 服务器代码:
    Future main() async {
    final HttpServer server = await HttpServer.bind("127.0.0.1", 8080);
    server.listen((HttpRequest request) async {

    print(request.headers.contentType);

    try {
    if (request.method == "GET") {
    String _requestData = ......
    Socket _socket = await Socket.connect('192.168.22.129', 3000);

    // READ FROM CSERVER
    _socket.listen((List<int> event) {
    _reply = new String.fromCharCodes(event).trim();
    });

    // WRITE TO SERVER
    _socket.add(utf8.encode('$_requestData\r\n'));

    // wait 1 seconds
    await Future.delayed(Duration(milliseconds: 1000));
    _socket.close();

    var _secureResponse = {};
    _secureResponse["Data"] = "$_reply";
    _secureResult = json.encode(_secureResponse);

    request.response.headers.contentType = new
    ContentType("application", "json", charset: "utf-8");
    request.response.write(_secureResult);
    request.response.close();

    }

    } finally {
    var _secureResponse = {};
    _secureResponse["Data"] = "ERROR";
    _secureResult = json.encode(_secureResponse);

    request.response.headers.contentType = new
    ContentType("application", "json", charset: "utf-8");
    request.response.write(_secureResult);
    request.response.close();
    }
    });
    }

    最佳答案

    参见https://api.dartlang.org/stable/2.1.0/dart-io/HttpHeaders-class.html

    你尝试过类似的东西吗

    request.headers.set(HttpHeaders.cacheControlHeader,
    'max-age=3600, must-revalidate');

    如果您要在Dart中构建服务器,我是否建议您使用 package:shelf-它更加易于使用。

    关于json - 如何在Dart Server中设置request.response的内容类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54493457/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com