【问题标题】:POST image to web service with Flutter使用 Flutter 将图像发布到 Web 服务
【发布时间】:2018-11-03 02:02:48
【问题描述】:

我目前正在使用 Flutter 和 Dart 尝试将图像发送到 Web 服务,然后等待 JSON 响应。下面的链接显示了我试图模仿的 Postman 请求。

An image of Postman with the headers required

An image of Postman with the body

我认为我遇到的问题是没有正确设置请求的标头,或者没有正确编码图像。

目前我收到 HTTP 400 错误。

我尝试关注these suggested solutions on StackOverflow,但收到了 HTTP 400 错误。

任何帮助将不胜感激!

【问题讨论】:

标签: rest web-services post dart flutter


【解决方案1】:

试试这个。如果你还没有的话,我建议你自己创建一个简单的 Dart 项目。这样您就可以在不需要手机模拟器等的情况下进行测试。

main() async {
  http.MultipartRequest request =
      new http.MultipartRequest('POST', Uri.parse(url));

  request.headers['Prediction-Key'] = '3f4a......'; // todo - insert real value

  request.files.add(
    new http.MultipartFile.fromBytes(
      'image',
      bytes,
      filename: 'somefile', // optional
      contentType: new MediaType('image', 'jpeg'),
    ),
  );

  http.StreamedResponse r = await request.send();
  print(r.statusCode);
}

如果文件在磁盘上,而不是在内存中,则改用fromPath 命名构造函数。尝试不同的媒体类型。我用过image/jpeg,但你可以试试application/octet-stream

顺便说一句,在您的第一个屏幕截图中,您显示了一个内容类型,但 Postman 忽略了这一点,因为整体内容类型被 multipart-form 覆盖。在 Postman 中取消选中该行以证明这一点。

最近在 SO 上还有另一个问题,服务器错误地期望标头区分大小写。在 postman 中,再次尝试使用小写的 prediction-key 以证明服务器不介意小写的标头(这是 Dart 使用的)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-13
    • 1970-01-01
    • 1970-01-01
    • 2010-11-09
    • 2014-04-09
    相关资源
    最近更新 更多