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

时间:2019-02-02 13:19:03

标签: json dart content-type serve

我如下图所示设置了镖服务器。我可以从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();
    }
  });
}

1 个答案:

答案 0 :(得分:1)

请参见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-更加用户友好。