2013-09-11 40 views
2

有沒有辦法設置的HttpClientRequestDart - 設置HttpClientRequest的mimetype

我試圖做一些單元測試,我創建的HttpClient一個實例,然後發送POST請求的數據的字節爲HttpServer,然後分析它的基礎上我設置了mimeType。類似這樣的:

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是不可變的。任何解決方法?

回答

3

根據docs,add()調用後不應修改數據。在添加數據之前設置標題將起作用:

r.headers.set(HttpHeaders.CONTENT_TYPE, 'application/json'); 
    r.add('{"val": 5}'.codeUnits);