颤振格式异常:意外字符(字符 1 处)



在颤振中,我使用了一个从数据库查询返回json响应的php文件,但是当我尝试解码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 飞镖依赖

使用下面的代码解决此问题。欲了解更多信息,请参阅此处。

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

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

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

我注意到此错误仅发生在模拟器中,而不发生在物理设备中。

如果您

正在使用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'
},

((

最后,

我在颤振中解决了问题,以这种方式请求数据:

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

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

错误来自颤振。这可能是因为您使用对象模型捕获 http 响应,但您的 api 响应实际上是字符串或其他。

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

如果您请求多部分或表单数据,请尝试使用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);
        });

这可能是由 Nginx 图像、文件大小限制引起的。这将覆盖您的 API 响应,并且您的 API 返回以下错误,而不是您自己定义的错误响应结构:

I/flutter (25662): <html>
I/flutter (25662): <head><title>413 Request Entity Too Large</title></head>
I/flutter (25662): <body>
I/flutter (25662): <center><h1>413 Request Entity Too Large</h1></center>
I/flutter (25662): <hr><center>nginx/1.20.0</center>
I/flutter (25662): </body>
I/flutter (25662): </html>

如果这是问题所在,您可以从服务器 Nginx 设置中更改允许的文件、图像大小以防止这种情况,或者在通过您的 API 发送图像文件之前检查并调整图像文件的大小。

在尝试修复之前,您需要查看真正的错误是什么。要确定真正的错误是什么,请在 json 解码并强制转换为映射线之前打印响应,如下所示:

debugPrint('Response body before decoding and casting to map: ');
      debugPrint(response.body.toString()); // this will print whatever the response body is before throwing exception or error

      Map responseMap = json.decode(response.body);
      debugPrint('responseMap is: ');
      debugPrint(responseMap.toString());
<</div> div class="one_answers">

对我来说,这是由于错误的网址。我错误地在我的基本 URL 后放置了两个/。

我不知道

为什么你在回复之前得到,但我认为它期望{作为第一个字符,这对你的场景来说不是真的。您是否自己添加了,或者您知道为什么它是响应的一部分?如果你能让它做出回应{"0":"PRUEBA","usu_nombre":"PRUEBA"}你应该在家安全。

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

这对我有用,http(http包(有问题,我用dart:io的httpClient替换了它

将来登录(字符串电子邮件,字符串密码(异步{

HttpClient httpClient = new HttpClient();
const url = "http://127.0.0.1/api/auth/login";
Map data = {
  "email": email,
  "password": password,
};
var body = json.encode(data);
HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));
request.headers.set('content-type', 'application/json');
request.add(utf8.encode(json.encode(data)));
HttpClientResponse response = await request.close();
String reply = await response.transform(utf8.decoder).join();
httpClient.close();
print(reply);

}

对我来说,将URL部分从:"http://localhost:3001/mypage"自"http://127.0.0.1:3001/mypage"解决了。

这对我捕获令牌并实现标头的主体很有用:

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

最新更新