You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 12:02:41