RedirectException: Redirect loop detected - flutter

I'm testing a request to get data from an URL using dio in my Dart code.
import 'package:dio/dio.dart';
class Api {
Dio dio = Dio();
var path = 'https://jsonplaceholder.typicode.com/users';
void getHttp() async {
try {
Response response = await dio.get(path);
print(response.data);
} catch (e) {
print(e);
}
}
}
In this case it brings the result correctly.
But, I actually need get data from this URL:
http://loterias.caixa.gov.br/wps/portal/loterias/landing/megasena/!ut/p/a1/04_Sj9CPykssy0xPLMnMz0vMAfGjzOLNDH0MPAzcDbwMPI0sDBxNXAOMwrzCjA0sjIEKIoEKnN0dPUzMfQwMDEwsjAw8XZw8XMwtfQ0MPM2I02-AAzgaENIfrh-FqsQ9wNnUwNHfxcnSwBgIDUyhCvA5EawAjxsKckMjDDI9FQE-F4ca/dl5/d5/L2dBISEvZ0FBIS9nQSEh/pw/Z7_HGK818G0KO6H80AU71KG7J0072/res/id=buscaResultado/c=cacheLevelPage/=/?timestampAjax=1588600763910
Using Postman I can access the data:
So, the problem is that, if I try to get data from that URL in my code, I get the following exception error:
I/flutter (23393): DioError [DioErrorType.DEFAULT]: RedirectException: Redirect loop detected
If this URL is redirecting, why is it working when using Postman? Anyway, how could I handle this redirected request in order to access data?

After a while, I noticed that the response to this request is coming as HTML and not as Json. So I needed to create a way to get DOM coming from the request, removing HTML tags and encoding string to Json.

Related

How to use the get() functin provided by the http package?

I'm trying to get data from a website that hosts Weather APIs (OpenWeatherMap), but as soon as I use the get() method, I get an error that says :
[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Failed host lookup: 'api.openweathermap.org'
Even tho the URL that I provided is working (I tested it, the API key is working), here is the code :
String url = "https://api.openweathermap.org/data/2.5/weather?lat=$latitude&lon=$longitude&appid=$apiKey";
// The latitude, longitude and apiKey aren't not null.
Uri uri = Uri.parse(url);
http.Response response;
try {
response = await http.get(uri);
} on Exception catch (e) {
print("Error when getting data from the url = $url"); // Im getting this line on the console,
// so the error is indeed the line above.
}
I fixed it. My phone had issues reaching Internet, so the code couldn't reach the URL provided.

http.get returns 404 "Route not found"

I am trying to use a public API to search movie titles via my Flutter/Dart app.
A minimal code snippet is this
static Future<AnimeSearchResult> fetchSearchResults(String searchTerm) async {
final response = await http.get(
Uri.https("kitsu.io", "/api/edge/anime?filter[text]=cowboy%20bebop"));
// https://kitsu.io/api/edge/anime?filter[text]=cowboy%20bebop
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return animeSearchResultsFromMap(response.body);
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
print(response.body);
throw Exception('Failed to load search results');
}
}
This will search and return an object back to a FutureBuilder Widget which then displays the results. (I have tested the UI and it is working on sample data)
Running the code, I get 404 error in my console
{"errors":[{"status":404,"title":"Route Not Found"}]}
Opening the link in my browser, it gives a JSON file as its supposed to do.
Trying to access the trending collection link using
final response = await http.get(Uri.https("kitsu.io", "/api/edge/trending/anime")); also works perfectly fine.
So I am suspecting there is some error in the way my URI is written for the search code. Precisely speaking, this line is at fault
final response = await http.get(Uri.https("kitsu.io", "/api/edge/anime?filter[text]=cowboy%20bebop"));
However I don't know what exactly is the problem.
Any help is appreciated!
Thank You!
I tried it this way, and it worked:
final response = await http.get(Uri.parse("https://kitsu.io/api/edge/anime?filter[text]=cowboy%20bebop"));
But await http.get(Uri.https resulted in the same error you are having.

flutter http request/response details including headers?

while http request details can easily be inspected in browser dev tools(for web app), I tried to explore, where I can find the same for requests sent in flutter App, but couldn't locate it.
like for example - I can see the actual response from api by print(response), but I am talking about complete request response including headers.
I am using VScode IDE for Flutter.
update:
I want to view the headers sent like response.header. reason for the same is like I am using flutter cahe manager and the issue I am facing is like I have set the -cache control max-age=1.
so the flutter should try to fetch the same every time I access the page, which it is doing, but it is serving the page from the cache and then fetching the request. so if there is any change is on server side, it doesn't reflect when first open the page, but shows the change on every second visit.
so what I want is like if the flutter gets 304 response from server, it will serve from the cache else it should serve from the fetched data. but it is not happening.
also the response.header is not showing response code like it is 200 or 304, so that flutter can fetch or serve from cache.
Actual code being used is like this:
Future<MyUserProfile> fetchMyUserProfile() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
final userid = prefs.getString('user_id');
var userProfile = await DefaultCacheManager().getSingleFile("url");
final response = await userProfile.readAsString();
if (response != '') {
print(userProfile);
// If the server did return a 200 OK response,
// then parse the JSON.
return MyUserProfile.fromJson(json.decode(response));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load Profile');
}
}
Don't wanna be rude, but the information you are looking for is quite easy to find... That is if you look in the right place, like official documentation.
https://api.flutter.dev/flutter/dart-io/HttpResponse-class.html
HttpResponse class ... headers → HttpHeaders Returns the response
headers. [...] read-only
http.Response response = await http.get(url...
print(response.headers);
EDIT: Answering the sub-question that was added to the original question.
To check what the status code is you simply access it via response.statusCode
Example:
http.Response response = await http.get(url...
if (response.statusCode == 200) {
// do something
} else if (response.statusCode == 304) {
// do something else
} else {
// handle this
}

flutter await GET response is not working

i have the follow function:
Future<Null> _loadORDER(String menssage) async {
var enZona =await ApiClient.zonaNum(menssage, apiKey);
print('enZona: $enZona');
if (enZona == 'true') {
_moveToNotification(context);
};
}
the print give me the follow message: "enZona: Instance of 'Response'"
if i test the response from postman of the api query is working normally and give me: true ,
then i hope that the print result will be : "enZona: true"
but i don't know how i do to wait the response of the ApiClient before continue with the conditional (if)
thanks for your help!
thanks i add the .body but i get the same response, the apiclient code is the follow:
final response = await http.get(baseUrl + '/shop/order/$message',
headers: {HttpHeaders.authorizationHeader: apiKey});
print("enZona: $response.body");
return response;
the print value for this is: enZona: Instance of 'Response'.body
You should do print("enZona: ${response.body}"); with the curly bracket, or you can assign response.body to some variable first.
final foo = response.body; print(foo);
If you go to the pub.dev documentation for the Response class, you will see that Response is more than the content of the response. It is a wrapper class that also includes information such as the statusCode of the response, the headers, etc.
When you saw the response in Postman, you only cared about the content of the response, that is, the body of the response. What you are looking for in your code is not the enZona instance of Response, but the body of the enZona response.
Therefore, you have to swap enZona by enZona.body when trying to access the contents of your response.

How to directly print JSON recieved in GET Request Body in Flutter

My intention is to make a GET request using the DIO or any similar HTTP client in order to receive a JSON data/body and print it to the console.
I have written the following code to achieve that.
fetchQuestion(String userIdentifier) async {
String urlToCall =
"someURLhere";
try {
Response response = await Dio().get(
urlToCall,
options: Options(headers: {
HttpHeaders.authorizationHeader: "Bearer " + userIdentifier,
}),
);
print(response.data);
} catch (e) {
print(e);
}
}
The problem with this code is, when I print response.data, only null is printed. Even though I am certain that the response data contains a JSON file.
I have checked on the backend, and I am getting a 200 status code. Additionally, printing response.headers does print the headers I expected. It is only the response.body that prints null.
Issues I have tried include
Using print(utf8.decode(response.data));
Using json.decode(response.data) -> In which case I get
NoSuchMethodError: The getter 'length' was called on null. error.
I would appreciate any kind of help regarding printing the JSON file received.
Have you printed just response to see what fields are in there.
I haven't used DIO but http package works fine for me:
import 'package:http/http.dart' as http;
...
final response = await http.get(Url);