使用Dart连接Realty Mole REST API时出错,请求排查问题
问题分析与修复方案
你遇到的400 Bad Request错误,核心原因是请求缺少API要求的必填参数。结合Realty Mole的API规则,/properties端点必须指定查询条件(如地址、经纬度等)才能返回有效数据,你的当前请求未提供任何查询参数,导致API无法处理请求并返回错误。
具体错误点
你使用的URL仅为基础端点地址https://realty-mole-property-api.p.rapidapi.com/properties,未附加任何必填的查询参数,API无法定位你要查询的房产范围,因此触发400错误。
修复步骤
- 添加必填查询参数
根据API要求,需在URL中加入至少一个有效查询条件,示例如下:
- 按地址查询:
var url = Uri.parse('https://realty-mole-property-api.p.rapidapi.com/properties?address=123+Main+St,Anytown,USA');
- 按经纬度查询:
var url = Uri.parse('https://realty-mole-property-api.p.rapidapi.com/properties?latitude=37.7749&longitude=-122.4194');
- 多参数组合(如城市+州+返回数量):
var url = Uri.parse('https://realty-mole-property-api.p.rapidapi.com/properties?city=Austin&state=TX&limit=10');
- 推荐使用安全的URL构建方式
为避免手动拼接URL时的编码错误,建议用DartUri类的queryParameters方法构建请求地址:
var url = Uri.https( 'realty-mole-property-api.p.rapidapi.com', '/properties', {'address': '123 Main St, Anytown, USA', 'limit': '5'} );
- 验证API密钥有效性
你的请求头中的X-RapidAPI-Key和X-RapidAPI-Host格式正确,若修复参数后仍报错,需检查密钥是否在RapidAPI后台正常启用、是否过期。
完整可运行示例代码
import 'package:http/http.dart' as http; Future<void> fetchProperties() async { final client = http.Client(); try { var url = Uri.https( 'realty-mole-property-api.p.rapidapi.com', '/properties', {'address': '1600 Pennsylvania Ave NW, Washington, DC 20500'} ); var response = await client.get( url, headers: { 'X-RapidAPI-Key': '51ced1b32emsh509f82e1d58ae16p1ad6e6jsn75d75166a8b4', 'X-RapidAPI-Host': 'realty-mole-property-api.p.rapidapi.com' }, ); if (response.statusCode == 200) { print('请求成功:${response.body}'); } else { print('请求失败,状态码:${response.statusCode},响应内容:${response.body}'); } } finally { client.close(); } }
内容的提问来源于stack exchange,提问作者LostTexan
相关产品推荐
相关产品推荐

