【问题标题】:Flutter response non-json structure form server getting html codeFlutter响应非json结构表单服务器获取html代码
【发布时间】:2019-05-23 11:26:03
【问题描述】:

当我连接到服务器以检查用户名和密码时,就像这个结构一样

{
"Username":"1",
"Password":"1"
}

我得到01,没有任何json格式,用户名和密码的第一个字母是大写字母,Username,Password,

现在我想用颤振和post http 动词得到这个响应

UserInformation

class UserInformation {
  String Username;
  String Password;

  UserInformation(this.Username, this.Password);

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> json = new Map<String, dynamic>();
    json['Username'] = this.Username;
    json['Password'] = this.Password;

    return json;
  }
}

LoginRepository类:

class LoginRepository {

  Future<int> authenticate(
      {@required String username, @required String password}) async {
    UserInformation userInformation = UserInformation(username, password);
    /*this line print {Username: 1, Password: 1}*/
    print(userInformation.toJson().toString());

    final response = await http.post(
        Constants.loginApi, body: userInformation.toJson());
    final responseString = jsonDecode(response.body);
    if (response.statusCode == 200) {
      return responseString;
    } else {
      throw Exception('fail to get response');
    }
  }
}

然后这个输出是来自服务器的响应:

[ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: FormatException: Unexpected character (at character 1)
<?xml version="1.0" encoding="utf-8"?>

【问题讨论】:

    标签: dart flutter


    【解决方案1】:

    首先:在访问 response.body 之前检查 statusCode。如果调用失败,response.body 将为空 String,jsonDecode 将失败。

    第二:由于您没有得到 json 格式的答案,因此无需使用响应调用 jsonDecode。 final int responseInt = response.body 应该足够了(也许你需要 int.parse(response.body); 需要测试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-16
      • 2019-10-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多