【问题标题】:How to solve 400 statusCode and Unexpected character (at character 1) error?如何解决 400 statusCode 和 Unexpected character (at character 1) 错误?
【发布时间】:2021-06-17 20:12:25
【问题描述】:

我有一个机器学习模型,它可以拍摄一张照片并返回一个预测,我将它上传到一个烧瓶服务器并在我使用 HTML 创建的网站上对其进行了测试,它可以工作,但是当我尝试将它与颤振应用程序一起使用时当我尝试从我的应用程序上传图片时,我收到此错误:Unhandled Exception: FormatException: Unexpected character (at character 1)。另外,我得到的 statusCode 是 400 .. 这些是我的代码。 任何帮助将不胜感激。

这是我创建烧瓶实例的python代码(当我尝试使用flutter应用程序建立连接时,我在我的cmd上运行它)

from flask import Flask, render_template, request, jsonify
import cv2
import numpy as np
import pandas as pd
import tensorflow
from tensorflow import keras
from tensorflow.python.keras import backend as k

app = Flask(__name__)

model = tensorflow.keras.models.load_model('model.h5')


@app.route('/')
def index():
    return render_template("index.html", data="hey")


@app.route("/prediction", methods=["POST"])
def prediction():

    
    img = request.files['img']  
    img.save("img.jpg")
    image = cv2.imread("img.jpg")
    image = cv2.resize(image, (224,224))
    image = np.reshape(image, (1,224,224,3))
    pred = model.predict(image)

    pred = pred > 0.5
    if(pred):
        predd="Malignant"
    else:
        predd="Benign"

    return jsonify({"prediction": predd,})
    
#this ip is my network's IPv4
#(I connected both my laptop and mobile to this WiFi while establishing the connection)
if __name__ == "__main__":
    app.run(debug=False,host='192.168.1.103',port=5000)

这是我在flutter中用来建立连接的代码

  sendImageToServer(File imageFile) async {
    var stream = new http.ByteStream(imageFile.openRead());
    stream.cast();
    var length = await imageFile.length();
    print(length);
    
    //this ip is my network's IPv4 
    //(I connected both my laptop and mobile 
    //to this WiFi while establishing the connection) 

    var uri = Uri.parse('http://192.168.1.103:5000/prediction');
    var request = new http.MultipartRequest("POST", uri);
    var multipartFile = new http.MultipartFile('file', stream, length,
        filename:
            basename(imageFile.path));

    request.files.add(multipartFile);
    request.headers["Content-Type"] = 'multipart/form-data';
    var streamedResponse = await request.send();
    var response = await http.Response.fromStream(streamedResponse);
    
    print(response);

    final Map<String, dynamic> responseJson =
        json.decode(response.toString()) as Map<String, dynamic>;
    print(responseJson.toString());

    pre = responseJson["prediction"];
    print(pre);

    setState(() {
      prediction = pre;
    });
  }

  Future getImage() async {
    final image = await picker.getImage(source: ImageSource.gallery);
    sendImageToServer(File(image.path));

    setState(() {
      fileImage = File(image.path);
      sendImageToServer(fileImage);
    });
  }

这也是我发送请求时在 cmd 上得到的结果

192.168.1.108 - - [20/Mar/2021 19:14:39] "←[1m←[31mPOST /prediction HTTP/1.1←[0m" 400 -

【问题讨论】:

    标签: python flutter flask request multipart


    【解决方案1】:

    更新答案

    所以你得到的异常是告诉你服务器无法理解你发送的请求,我认为现在的问题是你在这里发送请求的关键

    var multipartFile = new http.MultipartFile('file', stream, length,
            filename:
                basename(imageFile.path));
    

    在您的后端,您使用的是“img”键

    img = request.files['img']  
    

    所以这些应该是一样的,试试下面的

    var multipartFile = new http.MultipartFile('img', stream, length,
            filename:
                basename(imageFile.path));
    

    我真的希望这会奏效,还请查看以下链接,它可能会帮助您更多地了解问题,

    https://dev.to/carminezacc/advanced-flutter-networking-part-1-uploading-a-file-to-a-rest-api-from-flutter-using-a-multi-part-form-data-post-request-2ekm

    thisstackoverflow 问题

    旧答案

    错误消息没有说明错误的确切位置,因此请将您的代码添加到 try catch 块中,这样您就可以捕获任何抛出的异常并知道错误是什么。

    try {
    sendImageToServer(File imageFile) async {
        var stream = new http.ByteStream(imageFile.openRead());
        stream.cast();
        var length = await imageFile.length();
        print(length);
        
        //this ip is my network's IPv4 
        //(I connected both my laptop and mobile 
        //to this WiFi while establishing the connection) 
    
        var uri = Uri.parse('http://192.168.1.103:5000/prediction');
        var request = new http.MultipartRequest("POST", uri);
        var multipartFile = new http.MultipartFile('file', stream, length,
            filename:
                basename(imageFile.path));
    
        request.files.add(multipartFile);
        request.headers["Content-Type"] = 'multipart/form-data';
        var streamedResponse = await request.send();
        var response = await http.Response.fromStream(streamedResponse);
        
         //print(response);//this will print instance of response not the response itself
         // i cleared this a bit so we can trace where the error started from
         print(response.statusCode); // the status code of your response
         print(response.reasonPhrase); // the reason it failed "in case it did"
         print(response.body); // the body of the response -> this what you really interested in
    
      }
    } catch (e,s) {
      // this is your life saver, it will tell you everything 
      // you need to know to trace the error (well mostly :D)
      // note : this will catch any exceptions that is thrown in the code, this not related to the response
      // the (e) is error it self so your should print that to know what is the error
      print(e.toString());
      // the (s) is the stackTrace, it will tell you when and where the error 
      // happened, so you should also print it
      print(e.toString());
    }
    

    【讨论】:

    • 但是为什么省略这部分代码“ final Map responseJson = json.decode(response.toString()) as Map; print(responseJson. toString()); pre = responseJson["prediction"]; print(pre);"
    • 我们首先要确保请求成功,然后我们将添加它,您现在应该对错误了解更多,所以请添加您遇到的错误
    • I/颤动(20982):400 I/颤动(20982):*************************** ************************************ I/flutter (20982): 错误请求 I/flutter (20982): * ****************************************************** ********* I/flutter (20982): I/flutter (20982): 400 Bad Request I/flutter (20982):

      Bad Request

      I/flutter (20982):

      浏览器(或代理)发送了此服务器无法理解的请求。

      2 I/颤振 (20982): ****************************************** ******************
    • 请使用更新的代码和错误更新您的问题,以便任何人都可以提供帮助
    • 这行得通!非常感谢,非常感谢:)
    猜你喜欢
    • 2020-09-12
    • 2020-08-26
    • 1970-01-01
    • 2019-10-08
    • 1970-01-01
    • 2016-05-16
    • 2015-03-05
    • 2021-10-02
    • 2020-10-20
    相关资源
    最近更新 更多