如何在flutter中使用http包使用API

时间:2021-06-19 13:21:06

标签: flutter http http-headers

我正在尝试使用 API 来删除图像的背景。因此,我使用的是 http flutter 包。但我收到 <title>400 Bad Request</title> 错误。我该如何解决这个问题?

这是我试过的,

  removeBackGround(String imagePath) async {
    
    final body = {"image_file": imagePath};
    final headers = {"X-API-Key": "e5adebcdc77**************"};
    final response = await http.post(Uri.parse("https://sdk.photoroom.com/v1/segment"),
        body: body,
        headers: headers);

    if (response.statusCode == 200) {
      print("response  ok");
      
    } else {
      throw Exception('Failed to do network requests: Error Code: ${response.statusCode}\nBody: ${response.body}');
    }
  }

这是错误

E/flutter (14230): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: Exception: Failed to do network requests: Error Code: 400
E/flutter (14230): Body: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
E/flutter (14230): <title>400 Bad Request</title>
E/flutter (14230): <h1>Bad Request</h1>
E/flutter (14230): <p>Could not decode image, ensure image_file or image_file_b64 is set</p>

1 个答案:

答案 0 :(得分:0)

您可以通过使用 MulipartFormRequest

以稍微不同的方式使用 post 方法
Future removeBackGround(imagePath) async {
  var request = http.MultipartRequest(
      'POST', Uri.parse("https://sdk.photoroom.com/v1/segment"));
  await http.MultipartFile.fromPath(
    'image',
    imagePath,
    filename: 'image_$name.jpg',
  );
  // request.fields['companyName'] = name;
  // request.fields['own_id'] = id;
  request.headers["X-API-Key"] = "e5adebcdc77**************";

  var res = await request.send();
  return res.statusCode;
}

使用这种方法可以一次性上传图片和json数据。