11

对,所以我一直在研究需要通过标头进行基本身份验证并通过 HTTP Post 传递一些变量的东西。这是一个终端应用程序。

这就是我的代码的样子:

import 'package:http/http.dart' as http;
import 'dart:io';
void main() {
  var url = "http://httpbin.org/post";
  var client = new http.Client();
  var request = new http.Request('POST', Uri.parse(url));
  var body = {'content':'this is a test', 'email':'john@doe.com', 'number':'441276300056'};
  request.headers[HttpHeaders.CONTENT_TYPE] = 'application/json; charset=utf-8';
  request.headers[HttpHeaders.AUTHORIZATION] = 'Basic 021215421fbe4b0d27f:e74b71bbce';
  request.body = body;
  var future = client.send(request).then((response) => response.stream.bytesToString().then((value) => print(value.toString()))).catchError((error) => print(error.toString()));
}

我使用 httpbin 作为回显服务器,所以它告诉我我在传递什么。如果我不传递正文,或者如果我将字符串作为正文传递,我的代码可以正常工作。

显然这是因为 http.Request 中的 body 属性只接受字符串,而我正在尝试将映射传递给它。

我可以将其转换为字符串,它可能会起作用,但我仍然认为我的代码可以改进。不是从语法的角度来看,也不是从它如何处理未来的角度来看,但我不确定使用 http.dart 是正确的做法。

有人能指出我正确的方向吗?

提前致谢。

4

1 回答 1

19

JSON一个字符串。您需要将地图编码为 JSON 并将其作为字符串传递。

您可以使用bodyFields而不是body传递地图。
这样,您content-type的固定为"application/x-www-form-urlencoded".

DartDocpost说:

/// If [body] is a Map, it's encoded as form fields using [encoding]. The
/// content-type of the request will be set to
/// `"application/x-www-form-urlencoded"`; this cannot be overridden.

不久前我能够以这种方式发送 JSON 数据

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

编辑

import 'package:http/http.dart' as http;
import 'dart:io';
void main() {
  var url = "http://httpbin.org/post";
  var client = new http.Client();
  var request = new http.Request('POST', Uri.parse(url));
  var body = {'content':'this is a test', 'email':'john@doe.com', 'number':'441276300056'};
//  request.headers[HttpHeaders.CONTENT_TYPE] = 'application/json; charset=utf-8';
  request.headers[HttpHeaders.AUTHORIZATION] = 'Basic 021215421fbe4b0d27f:e74b71bbce';
  request.bodyFields = body;
  var future = client.send(request).then((response)
      => response.stream.bytesToString().then((value)
          => print(value.toString()))).catchError((error) => print(error.toString()));
}

生产

{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "content": "this is a test", 
    "email": "john@doe.com", 
    "number": "441276300056"
  }, 
  "headers": {
    "Accept-Encoding": "gzip", 
    "Authorization": "Basic 021215421fbe4b0d27f:e74b71bbce", 
    "Connection": "close", 
    "Content-Length": "63", 
    "Content-Type": "application/x-www-form-urlencoded; charset=utf-8", 
    "Host": "httpbin.org", 
    "User-Agent": "Dart/1.5 (dart:io)", 
    "X-Request-Id": "b108713b-d746-49de-b9c2-61823a93f629"
  }, 
  "json": null, 
  "origin": "91.118.62.43", 
  "url": "http://httpbin.org/post"
}
于 2014-06-12T11:59:36.997 回答