Home > Net >  http response returns 307 in flutter
http response returns 307 in flutter

Time:10-21

I was trying to call the post request to my API, I tested my API I could call the post request from python, in flutter I am facing an HTTP error 307.

Future<GetPrediction> askPrediction() async {
  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
    }),
  );

  if (response.statusCode == 200) {
    return GetPrediction.fromJson(jsonDecode(response.body));
  } else {
    log('Request failed with status: ${response.statusCode}.');
    throw Exception('Failed to fetch');
  }
}

CodePudding user response:

307 is a redirect, so you need to look at the response headers to see where it's redirecting. (The HTTP client shouldn't automatically follow a 307 as it requires a new POST.)

The headers show that the redirected URL is the same, but with the trailing slash removed. With that removed, a retried POST works.

  final params = {
    'ph': 0,
    'Hardness': 0,
    'Solids': 0,
    'Chloramines': 0,
    'Sulfate': 0,
    'Organic_carbon': 0,
    'Trihalomethanes': 0,
    'Turbidity': 0,
    'Conductivity': 0,
  };

  final response = await http.post(
    Uri.parse('https://water-quality-fast-api.herokuapp.com/predict'),
    body: utf8.encode(json.encode(params)),
  );

  print(response.body);
  • Related