Flutter使用HTTP库调用外部API时出现ClientException: XMLHttpRequest error
解决Flutter http.post调用API出现XMLHttpRequest error的问题
首先你代码里的URL字符串存在语法错误:'Here's the API link...'里的单引号嵌套未转义,这会直接导致Uri.parse解析失败,这大概率是触发报错的直接原因。先修复这个问题,把字符串内的单引号转义为\',或者改用双引号包裹整个URL,示例:
final response = await http.post( Uri.parse( "https://your-api-url.com?idOrdenNumero=$idOrdenNumero&idPunto=$idPunto"), );
如果修正语法后仍报错,再排查以下几个方向:
- 请求参数传递方式:你用POST请求却把参数拼在URL上,部分服务器对POST请求的参数位置有要求(比如必须放在请求体中)。可以尝试将参数移至body内:
final response = await http.post( Uri.parse("https://your-api-url.com"), body: { 'idOrdenNumero': idOrdenNumero, 'idPunto': idPunto, }, ); - 请求头缺失:Postman会自动添加部分默认请求头(如
Content-Type: application/x-www-form-urlencoded),Flutter的http.post虽默认也会添加,但可手动指定确认:final response = await http.post( Uri.parse("https://your-api-url.com"), headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: { 'idOrdenNumero': idOrdenNumero, 'idPunto': idPunto, }, ); - 证书信任问题:如果你的API使用自签名HTTPS证书,模拟器/真机的http库会拒绝请求,而Postman默认跳过证书校验所以能正常访问。测试环境下可在Android的
AndroidManifest.xml中添加android:usesCleartextTraffic="true",正式环境需配置证书信任。
内容的提问来源于stack exchange,提问作者JULIAN DAVID BECERRA RODRIGUEZ
相关产品推荐
相关产品推荐

