简体   繁体   English

通过flutter DIO包调用Post请求时抛出未处理的异常错误

[英]While calling Post request via flutter DIO package It throws unhandled Exception Error

I'm very new to the flutter, trying to send a POST request to the flask server consisting of image data using the flutter DIO package.我对颤振非常陌生,尝试使用颤振 DIO 包向由图像数据组成的烧瓶服务器发送 POST 请求。 I'm successfully able to call it through POSTMAN我可以通过 POSTMAN 成功调用它

sending post request in flutter app with DIO package as below使用 DIO 包在 flutter 应用程序中发送 post 请求,如下所示

   PickedFile? _image;

  //this is a code get image from Camera
  _imageFromCamera() async {
    PickedFile? image = await ImagePicker()
        .getImage(source: ImageSource.camera, imageQuality: 50);
    setState(() {
      _image = image;
    });
  }

  //this is a code get image from Gallery
  _imageFromGallery() async {
    PickedFile? image = await ImagePicker()
        .getImage(source: ImageSource.gallery, imageQuality: 50);
    setState(() {
      _image = image;
    });
  }


Future<String> uploadImage(PickedFile file) async {
    print('calling');
    Dio dio = new Dio();

    String fileName = file.path.split('/').last;
    FormData formData = FormData.fromMap({
      "file": await MultipartFile.fromFile(file.path,
          filename: fileName, contentType: new MediaType("image", "jpeg")),
    });
    var response = await dio.post("https://count-object.herokuapp.com/upload",
        data: formData);
    print(response.data['id']);
    return response.data['id'];
  }

I ran into error as below by sending a request as above fashion通过以上述方式发送请求,我遇到了如下错误

flutter ( 1731): [ERROR:flutter/lib/ui/ui_dart_state.cc(213)] Unhandled Exception: DioError [DioErrorType.response]: Http status error [400]
E/flutter ( 1731): #0      DioMixin.assureDioError
package:dio/src/dio_mixin.dart:819
E/flutter ( 1731): #1      DioMixin._dispatchRequest
package:dio/src/dio_mixin.dart:678
E/flutter ( 1731): <asynchronous suspension>
E/flutter ( 1731): #2      DioMixin.fetch.<anonymous closure>.<anonymous closure> (package:dio/src/dio_mixin.dart)
package:dio/src/dio_mixin.dart:1
E/flutter ( 1731): <asynchronous suspension>
E/flutter ( 1731):
E/flutter ( 1731): #0      DioMixin.fetch.<anonymous closure>
package:dio/src/dio_mixin.dart:618
E/flutter ( 1731): #1      _rootRunBinary (dart:async/zone.dart:1452:47)
E/flutter ( 1731): #2      _CustomZone.runBinary (dart:async/zone.dart:1342:19)
E/flutter ( 1731): #3      _FutureListener.handleError (dart:async/future_impl.dart:169:20)
E/flutter ( 1731): #4      Future._propagateToListeners.handleError (dart:async/future_impl.dart:719:47)
E/flutter ( 1731): #5      Future._propagateToListeners (dart:async/future_impl.dart:740:13)
E/flutter ( 1731): #6      Future._completeError (dart:async/future_impl.dart:550:5)
E/flutter ( 1731): #7      _SyncCompleter._completeError (dart:async/future_impl.dart:61:12)
E/flutter ( 1731): #8      _Completer.completeError (dart:async/future_impl.dart:33:5)
E/flutter ( 1731): #9      Future.any.onError (dart:async/future.dart:466:45)
E/flutter ( 1731): #10     _rootRunBinary (dart:async/zone.dart:1452:47)
E/flutter ( 1731): #11     _CustomZone.runBinary (dart:async/zone.dart:1342:19)
E/flutter ( 1731): #12     _FutureListener.handleError (dart:async/future_impl.dart:169:20)
E/flutter ( 1731): #13     Future._propagateToListeners.handleError (dart:async/future_impl.dart:719:47)
E/flutter ( 1731): #14     Future._propagateToListeners (dart:async/future_impl.dart:740:13)
E/flutter ( 1731): #15     Future._completeError (dart:async/future_impl.dart:550:5)
E/flutter ( 1731): #16     Future._asyncCompleteError.<anonymous closure> (dart:async/future_impl.dart:606:7)
E/flutter ( 1731): #17     _rootRun (dart:async/zone.dart:1428:13)
E/flutter ( 1731): #18     _CustomZone.run (dart:async/zone.dart:1328:19)
E/flutter ( 1731): #19     _CustomZone.runGuarded (dart:async/zone.dart:1236:7)
E/flutter ( 1731): #20     _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1276:23)
E/flutter ( 1731): #21     _microtaskLoop (dart:async/schedule_microtask.dart:40:21)
E/flutter ( 1731): #22     _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5)
E/flutter ( 1731):

at the server side terminal window throws this error在服务器端终端窗口抛出此错误

2021-06-23T12:14:34.147330+00:00 app[web.1]: 10.13.171.159 - - [23/Jun/2021:12:14:34 +0000] "POST /upload HTTP/1.1" 400 192 "-" "PostmanRuntime/7.26.8"
2021-06-23T12:14:40.603690+00:00 heroku[router]: at=info method=POST path="/upload" host=count-object.herokuapp.com request_id=76b0d4c5-76fc-4599-9801-10e8dc9259d8 fwd="157.50.34.16" dyno=web.1 connect=2ms service=2880ms status=200 bytes=141699 protocol=https

!UPDATE I tried catching the error it caught below error !UPDATE 我尝试捕捉它在错误下方捕捉到的错误

E/flutter (15704): [ERROR:flutter/lib/ui/ui_dart_state.cc(213)] Unhandled Exception: Exception: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
E/flutter (15704): <title>400 Bad Request</title>
E/flutter (15704): <h1>Bad Request</h1>
E/flutter (15704): <p>The browser (or proxy) sent a request that this server could not understand.</p>
E/flutter (15704):
E/flutter (15704): #0      _MyHomePageState.uploadImage
package:count_objects/main.dart:196
E/flutter (15704): <asynchronous suspension>
E/flutter (15704):

How can I send POST requests successfully as in POSTMAN and retrieve the image back as response?如何像在 POSTMAN 中一样成功发送 POST 请求并检索图像作为响应? any suggestion or guide on this will be helpful thanks :)对此的任何建议或指南都会有所帮助,谢谢:)

The post parameter key is wrong. post参数键错误。 In the postman screenshot, the post parameter is image where as in your code, it's file .在邮递员屏幕截图中, post 参数是image ,而在您的代码中,它是file Change the key to image .将密钥更改为image

Sample code:示例代码:

 File file=File("file_path_here");
  FormData formData = FormData.fromMap({
    "image":
    await MultipartFile.fromFile(file.path, filename:"file_name.jpg"),
  });

  var response = await Dio().post("https://count-object.herokuapp.com/upload", data: formData);

Surround your network calls in a try catch block在 try catch 块中包围您的网络调用

Future<String> uploadImage(PickedFile file) async {
    print('calling');
    Dio dio = new Dio();

    String fileName = file.path.split('/').last;
    FormData formData = FormData.fromMap({
      "file": await MultipartFile.fromFile(file.path,
          filename: fileName, contentType: new MediaType("image", "jpeg")),
    });
    try{
         var response = await dio.post("https://count- 
             object.herokuapp.com/upload",
        data: formData);
        print(response.data['id']);
        return response.data['id'];


    } on DioError catch(e){
        throw Exception(e.response?.data); 

   }
  }

throw Exception(e.response?.data); this will give you a hint of what's going wrong这会给你提示出了什么问题

只需检查您的请求是否正常,您可能会丢失错误请求响应的正确标头或正文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么通过python请求调用rest api时出现500 Internal Server Error? - Why am I getting 500 Internal Server Error when calling post rest api via python request? Django错误:未处理的异常 - Django Error: Unhandled Exception 调用 InvokeEndpoint 操作时发生错误 (InternalFailure):向模型发送请求时发生异常 - An error occurred (InternalFailure) when calling the InvokeEndpoint operation: An exception occurred while sending request to model 通过 std::system 调用 python 时出错 - Error while calling python via std::system Python Zeep Client请求在xml异常中引发错误 - Python Zeep Client request throws error in xml exception 处理来自Python包的未处理异常 - Handle unhandled exception from Python package Django on Production for POST 请求在计算引擎上引发服务器错误(500) - Django on Production for POST request throws Server Error(500) on compute engine Pythonanywhere-错误代码:未处理的异常 - Pythonanywhere - Error code: Unhandled Exception 发送带有数据的POST请求时出错 - Error while sending POST request with data drf - 尾随 / 在 url 中调用 post api 时抛出错误 - drf - trailing / in url throwing error while calling post api
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM