【问题标题】:Flutter FormatException: Unexpected character (at character 1)Flutter FormatException:意外字符(在字符 1 处)
【发布时间】:2019-09-04 09:19:17
【问题描述】:

在颤振中,我使用了一个 php 文件,它从 db 查询返回一个 json 响应,但是当我尝试解码 json 时,我得到了这个错误:

E/flutter ( 8294): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled
Exception: FormatException: Unexpected character (at character 1)
E/flutter ( 8294): [{"0":"PRUEBA","usu_nombre":"PRUEBA"}]
E/flutter ( 8294): ^

这是我的飞镖功能:

Future<String> iniciarSesion() async{
var usuario = textUsuario.text;
var password = textPassword.text;
var nombreUsuario;
var url ="http://192.168.1.37/usuario.php";

//Metodo post
var response = await http.post(
    url,
    headers:{ "Accept": "application/json" } ,
    body: { "usuario": '$usuario',"password": '$password'},
    encoding: Encoding.getByName("utf-8")
);
  List data = json.decode(response.body);
}

我的 php 文件中的代码:

<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');

include_once "Clases/conexion.php";

$usuario = $_POST['usuario'];
$password = $_POST['password'];

$consulta = "select usu_nombre
FROM usu_usuarios
WHERE usu_nusuario='$usuario'and usu_password='$password' and  usu_activo='SI'";

$mysql_obj = new Conectar();
$mysqli = $mysql_obj->crearConexion();

if($result = $mysqli->query($consulta)) {
if ($mysqli->affected_rows > 0) {
    while($row = $result->fetch_array()) {
        $myArray[] = $row;
    }
    header('Content-type: application/json');
    echo json_encode($myArray);
}else {
    header("HTTP/1.0 401 Datos Incorrectos");
    header('Content-type: application/json');
    $data = array("mensaje" => "Datos Incorrectos");
    echo json_encode($data);
}}
?>

我使用的是 HTTP dart 依赖

【问题讨论】:

  • 您好,我也遇到了同样的问题,请问您发现问题所在了吗?请问解决方法是什么?
  • @user2682025 嗨,请在下面查看我的答案:)

标签: json flutter http


【解决方案1】:

使用以下代码解决此问题。更多请参考here

var pdfText= await json.decode(json.encode(response.databody);  

【讨论】:

  • 完全使用 Flutter 2.0.6 引擎!非常感谢! [:
  • 这就是答案。谢谢。但为什么会出现这样的行为?
  • 这就像魅力谢谢人
【解决方案2】:

最后我用laravel解决了问题,以这种方式返回数据

return response()->json($yourData, 200, ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => 'utf-8'],
    JSON_UNESCAPED_UNICODE

我注意到这个错误只发生在模拟器中,而不是在物理设备中。

【讨论】:

    【解决方案3】:

    最后我解决了flutter中的问题,以这种方式请求数据:

    Map<String, String> headers = {
        'Content-Type': 'application/json;charset=UTF-8',
        'Charset': 'utf-8'
    };
    
    http.get('localhost:8000/users', headers: headers)
    

    【讨论】:

      【解决方案4】:

      如果您使用 Dio 并遇到这种错误,请添加:

       responseType: ResponseType.plain,
      

      给您的 dio 客户。 完整的dio客户端如下:

      final Dio _dio = Dio(BaseOptions(
      connectTimeout: 10000,
      receiveTimeout: 10000,
      baseUrl: ApiEndPoints.baseURL,
      contentType: 'application/json',
      responseType: ResponseType.plain,
      headers: {
        HttpHeaders.authorizationHeader:'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjQxNTU5MzYzLCJqdGkiOiJlOTBiZjIyYjI5YTg0YmRhYWNlZmIxZTY0Y2M2OTk1YyIsInVzZXJfaWQiOjF9.aDQzoYRawmXUCLxzEW8mb4e9OcR4L8YhcyjQIaBFUxk'
      },
      

      ) )

      【讨论】:

        【解决方案5】:

        如果您正在请求 Multipart 或 Form-data,请尝试使用 http.Response.fromStream(response) 将响应转换为简单的 http 响应

        完整代码:

         String baseUrl ="https://yourUrl.com";
                var uri = Uri.parse(baseUrl);
                var request = new http.MultipartRequest("POST", uri);
                request.headers.addAll(headers);
                var multipartFile = await http.MultipartFile.fromPath(
                    "file", videoFile.path);
                request.files.add(multipartFile);
                await request.send().then((response) {
                http.Response.fromStream(response).then((value) {
                print(value.statusCode);
                print(value.body);
                var cloudFlareResponse =
                CloudFlareApi.fromJson(json.decode(value.body));
                print(cloudFlareResponse.result.playback.hls);
                });
        

        【讨论】:

        • 我正在使用 Multipart,这对我来说就像魔术一样
        【解决方案6】:

        我不知道为什么您在回复之前会收到 ,但我认为它希望 { 作为第一个字符,这对于您的场景而言并非如此。您是否自己添加了,或者您知道为什么它是回复的一部分吗? 如果你能让它回复{"0":"PRUEBA","usu_nombre":"PRUEBA"},你应该是安全的。

        为什么要将数据保存为列表而不是字符串?通过将其作为字符串而不是列表,您可以避免响应中的方括号。

        【讨论】:

        • 感谢您的评论。我不知道这些符号来自哪里,但我确定我不会将它们添加到响应中。
        【解决方案7】:

        我在 Android 上遇到此错误是因为我使用了不安全的 http 连接,而没有在 AndroidManifest 中设置应用程序 android:usesCleartextTraffic="true"/。

        【讨论】:

          【解决方案8】:

          FormatException: Unexpected character (at character 1) Try again ^

          错误来自颤动。这可能是因为您使用 object model 捕获了 http 响应,但您的 api 响应实际上是 string 或其他。

          【讨论】:

            【解决方案9】:

            这对我来说可以捕获令牌并实现标头的正文:

            Future<List> getData() async {
               final prefs = await SharedPreferences.getInstance();
               final key = 'token';
               final value = prefs.get(key ) ?? 0;
             
               final response = await http.get(Uri.parse("https://tuapi"),  headers: {
               'Content-Type': 'application/json;charset=UTF-8',
               'Charset': 'utf-8',
               "Authorization" : "Bearer $value"
               });
               return json.decode(response.body);
            
               }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2021-03-30
              • 1970-01-01
              • 2020-06-16
              • 1970-01-01
              • 1970-01-01
              • 2019-08-17
              • 2022-07-31
              • 2020-03-07
              相关资源
              最近更新 更多