【问题标题】:Data not sending to api using http post数据未使用 http post 发送到 api
【发布时间】:2026-02-13 18:50:01
【问题描述】:

我想将 json 数据发布到 api,但是 api 没有从应用程序接收数据,尽管我从 php 脚本测试了 api 并且它工作正常。 “我认为 Content-Type 存在问题:application/json”,但我在代码中进行了设置。有什么解决办法吗?

BackEnd Code

--header 'Content-Type: application/json' \
--data-raw '{
  "username": "some data",
  "password": "some data",
  "mobile": "some data",
  "hash": "some data"
}'

颤振代码:

static Future<String> createNewUser(String url,{String body}) async{
    Map<String,String> headers = {
      "Content-type" : "application/json",
    };
    return await http.post(url,body: body,headers: headers).then((http.Response response){
      final int statusCode = response.statusCode;
      print(response.body);
        if( json == null){
          throw new Exception("Error while create new account");
        }
        return response.body;
    });
  }

编码的json

CreateUser createUser  = new CreateUser(
              username: "someData",
              password:"someData",
              mobile: "someData",
              hash: Validation.generateHash("someData"),
            );

            var body = json.encode(createUser.toMap());
            CreateUser.createNewUser(Config.URL_CREATE_NEW_USER,body: body).then((res){
              print(res);

【问题讨论】:

  • 您是否从 http.post 调用中得到任何响应?
  • @ArthurThompson 是的,来自 api 的响应没有发送数据。
  • 代码看起来正确,我会验证到达 createNewUser 的正文不是空的并且是有效的 json。
  • @ArthurThompson, createNewUser not empty 我打印了它并且正在生成有效的 json
  • 可能你的后端代码没有正确读取正文。

标签: flutter flutter-layout flutter-test


【解决方案1】:

尽量不要在一个Future 值上同时使用awaitthen

尝试以下:

static Future<String> createNewUser(String url,{String body}) async{
    Map<String,String> headers = {
      "Content-type" : "application/json",
    };
    http.Response response = await http.post(url,body: body,headers: headers)
    final int statusCode = response.statusCode;
    print(response.body);
    if( json == null){
      throw new Exception("Error while create new account");
    }
    return response.body;
  }

【讨论】:

  • 使用你的函数后也没有结果,在所有情况下服务器都以代码1010响应,这意味着数据没有发送到api。我认为后端接收json数据的问题
  • 哦,好的。没问题
  • 感谢朋友的帮助
最近更新 更多