我正在使用MultipartRequestfrom 上传文件package:http.我正在成功上传文件,但我想获取正在上传的文件的进度.我怎样才能做到这一点?我当前的代码看起来像这样
Future submitFile(var report, File file) async {
var uri = Uri.parse(endpoint + "v1/reports");
var request = http.MultipartRequest("POST", uri);
await addHeaders(request.headers);
request.fields.addAll(Report.toMap(report));
if (file != null)
request.files.add(await http.MultipartFile.fromPath(
'report_resource',
file.path,
));
String response = "";
await (await request.send()).stream.forEach((message) {
response = response + String.fromCharCodes(message);
});
return response;
}
Run Code Online (Sandbox Code Playgroud)
我搜索了解决方案,找到了这个.而这个职位是有点不相似,我想实现的,因为他是用不同的客户端的请求.
也许我没有在正确的道路上寻找.感谢帮助.
我想以最佳方式向同一服务器发出多个请求.所以我有
Future<List<Item>> getAllItems() async {
var client = new http.Client();
List<String> itemsIds = ['1', '2', '3']; //different ids
List<Item> itemList = [];
for (var item in itemsIds) {
//make call to server eg: 'sampleapi/1/next' etc
await client.get('sampleapi/' + item + '/next').then((response) {
//Do some processing and add to itemList
});
}
client.close();
return itemList;
}
Run Code Online (Sandbox Code Playgroud)
现在,api调用是一个接一个的.但api调用是相互独立的.什么是最好的实施方式,以避免异步等待地狱?
我正在使用 http 依赖项发出 http post 请求。我在回复中遇到以下错误。我在下面发布我的代码:
\n\nflutter: Error on line 1, column 32: Invalid media type: expected /[^()<>@,;:"\\\\\\/[\\]?={} \\t\\x00-\\x1F\\x7F]+/.\n \xe2\x95\xb7\n 1 \xe2\x94\x82 application/json;charset=utf-8;\n \xe2\x94\x82\n\n ^\nRun Code Online (Sandbox Code Playgroud)\n\n下面是我遇到错误的代码:
\n\ntry {\n String url = \'https://app.restroapp.com/\';\n Map<String, String> headers = {"Content-type": "application/json"};\n String json = \'{"device_id": "abaf785580c22722", "user_id": "", "device_token": "","platform":"android"}\';\n\n // make POST request\n Response response = await post(Uri.encodeFull(url), headers: headers, body: json);\n // check the status code for the result\n int statusCode = response.statusCode;\n // this API passes back …Run Code Online (Sandbox Code Playgroud) https://pub.dartlang.org/packages/shelf_web_socket显示了此示例
import 'package:shelf/shelf_io.dart' as shelf_io;
import 'package:shelf_web_socket/shelf_web_socket.dart';
void main() {
var handler = webSocketHandler((webSocket) {
webSocket.listen((message) {
webSocket.add("echo $message");
});
});
shelf_io.serve(handler, 'localhost', 8080).then((server) {
print('Serving at ws://${server.address.host}:${server.port}');
});
}
Run Code Online (Sandbox Code Playgroud)
我想知道如何将其与我的 HTTP 服务器初始化结合起来
import 'package:shelf/shelf.dart' as shelf;
import 'package:shelf/shelf_io.dart' as sIo;
import 'package:shelf_auth/shelf_auth.dart' as sAuth;
import 'package:shelf_auth/src/authentication.dart' as sAuth2;
import 'package:option/option.dart';
import 'package:shelf_web_socket/shelf_web_socket.dart' as sWs;
...
var authMiddleware = sAuth.authenticate(
[new MyAuthenticator()],
sessionHandler: new sAuth.JwtSessionHandler('bla', 'blub', new UserLookup()),
allowHttp: true,
allowAnonymousAccess: false);
var handler = const shelf.Pipeline()
.addMiddleware(shelf.logRequests())
.addMiddleware(authMiddleware) …Run Code Online (Sandbox Code Playgroud) 我正在尝试构建一个Flutter应用程序,我需要使用dart http库进行HTTP调用.所以这是我用来拨打电话的剪辑,
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
Future<List> getData() async {
List data = new List();
var httpClient = new HttpClient();
var request = await httpClient.get("localhost", 5000, '/search?query=hello');
var response = await request.close();
if (response.statusCode == HttpStatus.OK) {
var jsonString = await response.transform(utf8.decoder).join();
data = json.decode(jsonString);
print(data);
return data;
} else {
return data;
}
}
Run Code Online (Sandbox Code Playgroud)
现在getData()从我的代码调用,这是我得到的错误
E/flutter (30949): [ERROR:topaz/lib/tonic/logging/dart_error.cc(16)] Unhandled exception:
E/flutter (30949): SocketException: OS Error: Connection refused, …Run Code Online (Sandbox Code Playgroud) 我目前正在尝试访问 Flutter 中需要 JWT 访问令牌进行授权的 Web API。访问令牌在一定时间后过期。
可以使用单独的刷新令牌请求新的访问令牌。现在,只要请求返回 401 响应,就会执行此访问令牌刷新。之后,应使用新的访问令牌重试失败的请求。
我在这最后一步遇到了麻烦。好像http.BaseRequest只能发送一次。我将如何使用新令牌重试 http 请求?
正如dart http readme 中所建议的,我创建了一个子类http.BaseClient来添加授权行为。这是一个简化版本:
import 'dart:async';
import 'package:http/http.dart' as http;
class AuthorizedClient extends http.BaseClient {
AuthorizedClient(this._authService) : _inner = http.Client();
final http.Client _inner;
final AuthService _authService;
Future<http.StreamedResponse> send(http.BaseRequest request) async {
final token = await _authService.getAccessToken();
request.headers['Authorization'] = 'Bearer $token';
final response = await _inner.send(request);
if (response.statusCode == 401) {
final newToken = await _authService.refreshAccessToken();
request.headers['Authorization'] = 'Bearer $newToken'; …Run Code Online (Sandbox Code Playgroud) 我试图了解dart:io库中的http包和HttpClient类之间的区别。我的目的是知道何时应该使用哪个。我看到他们两个以前显然都做过同样的事情。
我看过以下问答:
到目前为止,我认为这是正确的,但我的理解很模糊:
http是高级别,HttpClient是低级别(源)http可以发出发布请求,但HttpClient不能(来源)http和HttpClent(与HttpClientRequest)可以使GET和POST请求(源)http并HttpClent可以在客户端和服务器上使用综上所述,我想说一个人可以做其他人可以做的任何事情,但是使用该http程序包比较容易,因为这个程序包的层次更高。该摘要正确吗?
我正在尝试为下载文件制作一个进度条指示器,但是如果我向 中添加一个侦听器StreamedResponse,管道会起作用,但不会完成它的未来。
final client = new http.Client();
http.StreamedResponse response = await client.send(http.Request("GET", Uri.parse('someurl')));
var received = 0;
var length = response.contentLength;
//if I remove this listener, the await below gets completed
var listen = response.stream.listen((List<int> bytes) {
received += bytes.length;
print("${(received / length) * 100} %");
});
var sink = downloadFile.openWrite();
await response.stream.pipe(sink);
listen.cancel();
sink.close();
Run Code Online (Sandbox Code Playgroud)
在github 上,他们已经建议某人它应该可以工作,但在StreamedResponse 文档中,它保持不变This should always be a single-subscription stream.。因此,添加一个侦听器来计算百分比似乎会以某种方式产生错误StreamedResponse。关于如何让它发挥作用的任何想法?
我们处于生产应用程序面临以下套接字异常并且在此之后无法执行任何其他网络操作的情况。
DioError [DioErrorType.DEFAULT]: SocketException: Failed host lookup: ‘xyz.abc.com’ (OS Error: nodename nor servname provided, or not known, errno = 8)
Run Code Online (Sandbox Code Playgroud)
注意:反复遇到一位使用 iPhone X、iOS 14.4 的用户
我们使用Dio作为网络客户端,使用Retrofit,它在内部使用来自 dart 的 HttpClient。使用Dio,模拟环境无法重现异常,但直接使用HttpClient,可以在iOS模拟器中使用以下代码重现相同的异常。
HttpClient userAgent = new HttpClient();
bool run = true;
while (run) {
try {
await userAgent.getUrl(Uri.parse('https://www.google.com'));
print('Number of api executed');
} catch (e) {
print(e);
if (e is SocketException) {
if ((e as SocketException).osError.errorCode == 8)
print('***** Exception Caught *****');
}
}
}
Run Code Online (Sandbox Code Playgroud)
一旦抛出异常,HttpClient 就无法从该陈旧状态中恢复,并且所有其他 API 请求都开始失败并出现相同的错误。 …
我正在尝试使用 API 与 PHP 后端进行通信,但无法到达响应正文。
我需要到达消息,并在 UI 中显示错误,问题是response.stream它的类型是 Bytesreem,我无法将其转换为 Map
我的代码:
Future<void> _authenticateUp(String email, String password,
String passwordconfirmation, String username, String name,
{String phonenumber}) async {
var headers = {
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
};
var request = http.MultipartRequest('POST', Uri.parse('$siteUrl/register'));
request.fields.addAll({
'email': email,
'password': password,
'password_confirmation': passwordconfirmation,
'username': username,
'name': name,
'phone_number': phonenumber
});
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
try {
if (response.statusCode == 200) {
await response.stream.bytesToString().then((value) {
print(value);
});
} else {
// here …Run Code Online (Sandbox Code Playgroud)