2

有没有办法设置mimeTypeof HttpClientRequest

我正在尝试做一些单元测试,在其中创建一个实例,HttpClient然后向 a 发送一个带有数据字节的发布请求,HttpServer然后根据mimeTypeI 设置对其进行解析。像这样的东西:

import 'dart:io';

void main() {
  HttpServer.bind('localhost', 8080)
    .then((HttpServer server) {
      server.listen((HttpRequest request) {
        String mimeType = request.headers.contentType.mimeType;
        if (mimeType == 'application/json') {
          // parse bytes of data to json and then to map
        } else if (mimeType == 'text/plain') {
          // parse bytes of data to string
        }
        // do something with data
        // close response
      });
    });
  HttpClient client = new HttpClient();
  client.open('POST', '127.0.0.1', 8080, '/')
    .then((HttpClientRequest r) {
      r.add('{"val": 5}'.codeUnits);
      // already tried both
      r.headers.set(HttpHeaders.CONTENT_TYPE, 'application/json'); // doesn't work
      r.headers.contentType = ContentType.parse('application/json'); // doesn't work
      r.close();
    });
}

所以HttpHeaders是不可变的。任何解决方法?

4

1 回答 1

3

根据文档,在 add() 调用后不应修改数据。在添加数据之前设置标题将起作用:

  r.headers.set(HttpHeaders.CONTENT_TYPE, 'application/json');
  r.add('{"val": 5}'.codeUnits);
于 2013-09-11T14:29:56.770 回答