数据未使用http帖子发送到api

问题描述 投票:0回答:1

我想将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"
}'

Flutter代码:

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;
    });
  }

Encoded 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);

flutter flutter-layout flutter-test
1个回答
0
投票

不要在一个await值上同时使用thenFuture

尝试以下内容:

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;
  }
© www.soinside.com 2019 - 2024. All rights reserved.