How to directly print JSON recieved in GET Request Body in Flutter - 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);

Related

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.

RedirectException: Redirect loop detected

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.

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.

Exception has occurred. FormatException (FormatException: Unexpected character (at character 1) <HTML></HTML> ^ )

I'm creating a news application, and I get my data by JSON and in each running my app get me a crash on (response HTTP) I can't understand it:
Exception has occurred. FormatException (FormatException: Unexpected character (at character 1
<HTML></HTML> ^ )
Code:
import 'package:http/http.dart' as http;
import 'dart:convert';
class Category {
int id;
String title;
Category({
this.id,
this.title
});
static Future<List<Category>> getCategories() async {
http.Response response = await http.get("url JSON"); // <- Here carash
Map<String, dynamic> map = json.decode(response.body);
List<Category> list = [];
for(var map in map['categories']){
list.add(
Category(id: map['id'], title: map['title'])
);
}
return list;
}
}
You're doing something wrong with request I think and the api does not handle that error and throws the error as html as I guess. Anyway, the way you are decoding is not the proper way.
Few points to keep in mind when you are doing http request:
Most importantly study data type (HTML / JSON) and structure of the
data. By printing to the console or great way to use curl request or postman.
Always make sure to wrap your json.decode() with a try - catch
block, When there is a error, you can properly see what's going on
with your code.
Make sure that your response status code is 200. And handle your data occordingly.
And before iterate over the decoded response, ensure that it contains
value.
If you don't know the type or if you are not
sure, without using static type to assign decoded response body use
final (Dont always use dynamic type, my suggestion for only for situations like this). This will help you with FormatException like the situation you are facing.
Last but not least, when you want to check error messages with status code. As example,
when checking expired jwt, you are getting 500 as status code.
So only checking status code is not enough in that situation
because of 500 means internal server error.
Ex:
List list = [];
try {
final decodedBody = json.decode(response.body); // when you have error messages with response, you can also check message with status code
debugPrint(decodedBody?.toString());
if (response.statusCode == 200) {
if (decodedBody != null && map['categories'] != null) { // you can also check the data type you want here ex: (map is List)
for(var map in map['categories']){
list.add(Category(id: map['id'], title: map['title']));
}
// Below is another thrilled way to do this
// list = decodedBody.map['categories']((item) => Category(id: item['id'], title: item['title'])).toList();
}
}
} catch(e, _) {
debugPrint(e.toString());
}
Wish this helpful. Follow above steps and if there any other error let me know.
The response that you are receiving is not a JSON and so your JSON can't be decoded.
Your server is returning some HTML tags and this means you might be requesting to the wrong URL, please check the URL in PostMan or Browser and see response.

Dio's get request returning incomplete data

I'm making a get request with the Dio library (https://pub.dev/packages/dio), but apparently it is not getting all the data in the coming json.
Here's the request:
This is the json that comes from it:
But this is the Response object I get from this request:
:
Note how the "headers" field in the json has substantially more values than my headers field in response.data.
Am I doing something wrong here?
You are returning response without extract it's content. That's OK, but you need to extract the body from response where you are calling this method:
http.Response response = await _yourApi.getData();
if (response.statusCode == 200) {
//Do what you want with body
final body = response.body;
}