Flutter调用自定义API返回HTTP 307错误,Python调用正常求助
解决Flutter调用API出现HTTP 307错误的问题
原因分析
HTTP 307是临时重定向状态码,说明请求被服务器要求转向其他地址。Python的请求库(如requests)默认会自动跟随POST请求的重定向,但Flutter的http.post方法默认不自动处理POST请求的重定向,这就是Python调用正常、Flutter报错的核心原因。
修复方案
方案1:修正请求URL
多数情况是URL末尾斜杠导致的重定向,尝试去掉URL末尾的斜杠:
Uri.parse('https://water-quality-fast-api.herokuapp.com/predict')
方案2:手动处理重定向
如果必须保留原URL,可手动获取重定向地址并重新发送请求:
Future<GetPrediction> askPrediction() async { var response = await http.post( Uri.parse('https://water-quality-fast-api.herokuapp.com/predict/'), headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(<String, double>{ "ph": 0, "Hardness": 0, "Solids": 0, "Chloramines": 0, "Sulfate": 0, "Conductivity": 0, "Organic_carbon": 0, "Trihalomethanes": 0, "Turbidity": 0 }), ); // 处理307临时重定向 if (response.statusCode == 307) { final redirectUrl = response.headers['location']; if (redirectUrl != null) { response = await http.post( Uri.parse(redirectUrl), headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(<String, double>{ "ph": 0, "Hardness": 0, "Solids": 0, "Chloramines": 0, "Sulfate": 0, "Conductivity": 0, "Organic_carbon": 0, "Trihalomethanes": 0, "Turbidity": 0 }), ); } } if (response.statusCode == 200) { return GetPrediction.fromJson(jsonDecode(response.body)); } else { log('Request failed with status: ${response.statusCode}.'); throw Exception('Failed to fetch'); } }
方案3:开启自动跟随重定向(注意风险)
Flutter的http.post可通过followRedirects参数开启自动重定向,默认对POST请求该参数为false,手动设为true即可:
final response = await http.post( Uri.parse('https://water-quality-fast-api.herokuapp.com/predict/'), headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(<String, double>{ "ph": 0, "Hardness": 0, "Solids": 0, "Chloramines": 0, "Sulfate": 0, "Conductivity": 0, "Organic_carbon": 0, "Trihalomethanes": 0, "Turbidity": 0 }), followRedirects: true, maxRedirects: 5, // 限制重定向次数,避免死循环 );
注意:自动跟随POST重定向可能遇到服务器不规范处理,导致请求方法被改为GET,优先推荐方案1或2。
内容的提问来源于stack exchange,提问作者Laxmi kanth Reddy
相关产品推荐
相关产品推荐

