Flutter http Package POST API call return 302 instead of 200, post is success in DB

Issue

Hi when I make an API post request via Postman getting the correct status code as 200 but make the same api call with flutter/http package (v0.12.0+4) or DIO (v3.0.9) package I’m getting status code as 302, but the post was successful and the data was saved on the DB. how can I get the status 200 for this or is there a better way to handle redirect in post

Found these git hub issues, but no answer on how to fix this
https://github.com/dart-lang/http/issues/157

https://github.com/dart-lang/sdk/issues/38413

Code making API post
       ........... 

      final encoding = Encoding.getByName('utf-8');
        final headers = {
          HttpHeaders.contentTypeHeader: 'application/json; charset=UTF-8',
          HttpHeaders.acceptHeader: 'application/json',
        };
        //String jsonBody = jsonEncode(feedRequest.toJsonData());
        String jsonBody = feedRequest.toJsonData();
        print('response.SubmitFeedApiRequest>:' + feedRequest.toJsonData());
        print('jsonBody:>' + jsonBody);

        String url ='https://myapp';

        final response = await http.post(url,
            headers: headers, body: jsonBody, encoding: encoding);

        print('response.statusCode:' + response.statusCode.toString());

        if (response.statusCode == 200) {
          print('response.data:' + response.body);
        } else {
          print('send failed');
        }
     ...............

Postman Screenshot
enter image description here

===UPDATED WORKING CODE AS PER @midhun-mp comment

 final response = await http.post(url,
        headers: headers, body: jsonBody, encoding: encoding);

    print('response.statusCode:' + response.statusCode.toString());

    if (response.statusCode == 302) {
      //print('response.headers:' + response.headers.toString());
      if (response.headers.containsKey("location")) {
        final getResponse = await http.get(response.headers["location"]);
        print('getResponse.statusCode:' + getResponse.statusCode.toString());
        return SubmitFeedApiResponse(success: getResponse.statusCode == 200);
      }
    } else {
      if (response.statusCode == 200) {
       // print('response.data:' + response.body);
        return SubmitFeedApiResponse.fromJson(json.decode(response.body));
      }
      return SubmitFeedApiResponse(success: false);
    }
  }

Solution

The 302 is not an error, it’s a redirection status code. The http package won’t support redirection for POST request.

So you have to manually handle the redirection. In your code you have to add a condition for status code 302 as well. When the status code is 302, look for the redirection url in the response header and do a http GET on that url.

Answered By – Midhun MP

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.