while hitting an API Request throws 302 status code how to solve this

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'); } } 

2 Answers

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.)

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.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like