我正忙着组建一个能够进行http POST的Dart命令行客户端.我知道我不能使用dart:html库并且必须使用dart:io
开始似乎很简单:
HttpClient client = new HttpClient();
client.getUrl(Uri.parse("http://my.host.com:8080/article"));
Run Code Online (Sandbox Code Playgroud)
问题是:正确的语法和顺序是什么使它HttpClient做一个POST并能够将JSON编码的字符串传递到这篇文章?
我需要能够从私人服务器下载和显示图像。我发送的请求需要包含一个带有 content-type 的标头和一个带有 sessionToken 和 userId 的正文。服务器使用内容类型应用程序/八位字节流的二进制流进行响应。
这是我现在拥有的代码:
Future<Null> _downloadFile(String url, String userId, sessionToken) async {
Map map = {'token': sessionToken, 'UserId': userId};
try {
var request = await httpClient.getUrl(Uri.parse(url));
request.headers.set('content-type', 'application/json');
request.add(utf8.encode(json.encode(map)));
var response = await request.close();
var bytes = await consolidateHttpClientResponseBytes(response);
await _image.writeAsBytes(bytes);
userImage(_image);
}
catch (value){
print(value);
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试读取响应时,出现此错误:HttpException:内容大小超出指定的内容长度。已写入 72 个字节,而预期为 0。
我试图无休止地在谷歌上搜索如何使用流从服务器下载文件,但我找不到任何东西。我需要的是类似于.NET中的位图类的东西,它可以接收流并将其转换为图像。
有谁能够帮助我?这将不胜感激。
我开始尝试使用HTTPRequest,dart:html但很快意识到这在控制台应用程序中是不可能的.我做了一些谷歌搜索,但找不到我想要的东西(只找到HTTP服务器),是否有通过控制台应用程序发送正常HTTP请求的方法?
或者我是否必须使用套接字的方法并实现我自己的HTTP请求?
我正在使用 dart 中的 HttpClient(dart:io 包,而不是 dart:http),并且我想发送 HTTPS 请求。有没有办法做到这一点?我似乎找不到一种方法可以让我做到这一点。
我意识到目前至少有三个“官方”Dart 库允许我执行 HTTP 请求。更重要的是,其中三个库(dart:io(类 HttpClient)、package:http 和 dart:html)都有不同的、不兼容的 API。
截至今天,package:html 不提供此功能,但在其 GitHub 页面上,我发现它旨在与 dart:html 100% API 兼容,因此这些方法最终将添加到那里。
哪个包提供了最未来证明和平台独立的 API 来在 Dart 中发出 HTTP 请求?
是包:http吗?
import 'package:http/http.dart' as http;
var url = "http://example.com";
http.get(url)
.then((response) {
print("Response status: ${response.statusCode}");
print("Response body: ${response.body}");
});
Run Code Online (Sandbox Code Playgroud)
是 dart:html/package:html 吗?
import 'dart:html';
HttpRequest.request('/example.json')
.then((response) {
print("Response status: ${response.status}");
print("Response body: ${response.response}");
});
Run Code Online (Sandbox Code Playgroud)
还是飞镖:io?
import 'dart:io';
var client = new HttpClient();
client.getUrl(Uri.parse("http://www.example.com/"))
.then((HttpClientRequest request) {
// Optionally set up headers...
// Optionally write to the request …Run Code Online (Sandbox Code Playgroud)