gpt4 book ai didi

flutter - Dart/Flutter POST 请求和流响应

转载 作者:行者123 更新时间:2023-12-05 03:51:05 24 4
gpt4 key购买 nike

我想向相机发送 POST 请求并接收返回的 motionJPEG 流。我正在使用 Dart http包裹。据我所知,我不能使用 http.post接收流作为响应。我正在尝试使用 http.Client.send .我不知道如何为 http.Request 创建合适的正文和标题.

大多数 IP 摄像机使用 GET 来访问 MotionJPEG 字节流。但是,我使用的相机是 RICOH THETA 相机,它需要将带有有效负载的 POST 命令发送到相机。如果有人知道如何使用 dart http 模块创建正确的 POST 请求以返回带有 header 和正文的流,请提供帮助。

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

main() async {
Uri url = Uri.parse('https://192.168.1.1/osc/commands/execute');
var request = http.Request('POST', url);

Map<String, String> bodyMap = {'name': 'camera.getLivePreview'};
request.body = jsonEncode(bodyMap);

Map<String, String> headers = {"Content-type": "application/json"};
http.Client client = http.Client();
StreamSubscription videoStream;
client.head(url, headers: headers);
client.send(request).then((response) {
var startIndex = -1;
var endIndex = -1;
List<int> buf = List<int>();
videoStream = response.stream.listen((List<int> data) {
for (var i = 0; i < data.length; i++) {
print(data[i]);
}
});
});
}

最佳答案

我遇到了同样的问题,你所做的实际上是正确的,但是 HTTP 包修改了你的请求并添加了一些额外的细节,所以最好使用 dart:io HttpClient.

示例代码

import 'dart:convert';
import 'dart:io';
import 'dart:async';

main() async {
String url =
'https://pae.ipportalegre.pt/testes2/wsjson/api/app/ws-authenticate';
Map map = {
'data': {'apikey': '12345678901234567890'},
};

print(await apiRequest(url, map));
}

Future<String> apiRequest(String url, Map jsonMap) async {
HttpClient httpClient = new HttpClient();
HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));
request.headers.set('content-type', 'application/json');
request.add(utf8.encode(json.encode(jsonMap)));
HttpClientResponse response = await request.close();
// todo - you should check the response.statusCode
String reply = await response.transform(utf8.decoder).join();
httpClient.close();
return reply;
}

为了更清楚地了解 this stackoverflow 帖子

关于flutter - Dart/Flutter POST 请求和流响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63195155/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com