1

I'm hitting an API using http dart library while doing this I'm getting 302 status code. I know that 302 status code is for redirects, can you please say how can i enable redirects in http post method. I have used the following code:

  Future<LoginModel> login(String username, String password) async {
    var client = new http.Client();
    final response =
        await client.post(LOGIN_URL +"username=Student&password=2018" ,
            headers: {'Content-type': 'application/json',
            'Accept': 'application/json'});
    if (response.statusCode == 200) {
      return LoginModel.fromJson(json.decode(response.body));
    } else {
      throw Exception('Failed to load post');
    }
  }
Android
  • 99
  • 1
  • 1
  • 13

3 Answers3

2

302 is a status code returned by the server to indicate that the client should retry the request using a different URL. It's a way to redirect the client to a different endpoint.

The problem is that only GET (or HEAD) requests can be retried automatically. You are using a POST.

If the 302 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.

A well-behaved API should probably not issue 30X in response to a POST, but it is. The way to get around this is to make a new http request with the redirected URL. (You might want to put it in a while loop to keep following the redirects until you get to 200, or some error, or reach a timeout/limit.)

Richard Heap
  • 48,344
  • 9
  • 130
  • 112
0

add header with "Accept":"application/json" . henceforth it will only return json data otherwise it will prompt to redirect with html url, default dio configuration does not have response type so you have to mention it in header.

A.K.J.94
  • 492
  • 6
  • 14
0

This is because of some issue with the URL that you use. status code 302, says that the URL you are using has been moved or redirected. May be the loginurl that you are using has certificates now and using https:// instead of http://

Ramya Musunuru
  • 177
  • 1
  • 5