In Dart on server-side, how to set headers in HttpClient

核能气质少年 提交于 2020-01-04 03:00:48

问题


I am trying to use the Dart HttpClient class (io library / server-side!) and I can not think how to do the EQUIVALENT of the Dart (client-side) call to setRequestHeader.

Specifically I want to set "Content-type" to "application/json"

as per this line (from Client-side):

request.setRequestHeader("Content-type", "application/json");

I'm using the format:

new HttpClient().postUrl(Uri.parse(url))      
       .then((HttpClientRequest  request)  => request.close())
       .then((HttpClientResponse response) => response.transform(new Utf8Decoder()).listen(_set_dbStats));

and when I try to insert:

.then((HttpClientRequest  request) => request.head("Content-type", "application/json"))

I'm informed (in the Dart editor) that head is not a method for request... (although I see it in the API?!) Could this be related to it being used as a POST?

Thanks in advance!


回答1:


Here is a snippet of working code that evolved from numerous tests and dealing with some issues that were outside the scope of the original question.

Guenter Zoechbauer heroically worked with me off-line to get this dones, I could not find any examples of 1. Server Side, 2. POST 3. HTTP commands using Headers, this format permits this...

import 'package:http/http.dart' as http;

String url = "https://whatever.com";
return new http.Client()
   .post(url, headers: {'Content-type': 'application/json'},
    body: '{"distinct": "users","key": "account","query": {"active":true}}')
   .whenComplete(() => print('completed'))
   .then((http.Response r) => r.body);
}



回答2:


import 'package:http/http.dart' as http;

new http.Client().head(headers will go here)


来源:https://stackoverflow.com/questions/23967250/in-dart-on-server-side-how-to-set-headers-in-httpclient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!