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.
Related
I would like to be able to read the content of a .bin file stored at a url of the form https://something/file.bin.
I tried with the http package, but the http.get doesn't work, the exception "XMLHttpRequest error." is thrown :
try {
String url = '${constants.backPrefix}${file.gpxFilePath}';
final response = await http.get(Uri.parse(url));
if(response.statusCode == 200) {
debugPrint(response.body);
} else {
debugPrint("Incorrect statusCode : ${response.statusCode}");
}
} catch (e) {
debugPrint("Exception : $e");
}
When I run this code I have :
Exception : XMLHttpRequest error.
I have no problem to access the rest of the back end (images and JSONs). I'm sure it's the correct url because when I write the url in my browser I can access to the file. The person who develops the back end told me that it could be a CORS problem.
I'm new to flutter and mobile/web development in general so maybe there's something I'm misunderstanding.
Thank you !
I have a problem regarding fetching data or using the request API in local in flutter.
I tried to send a request using postman and it works, but when I'm trying to request in flutter, it gives me Connection refuse.
I'm using http package of flutter
This is the error, but i also tried jsonplaceholder api and it works.
I/flutter (10134): 5004/profile URI :>> http://127.0.0.1:5004/profile/v1.0/channels/1?includes=createdByProfile,joinedProfiles
I/flutter (10134): error :>> Connection refused
Heres my code:
Future loadData() async {
try {
var data = await http.get(Uri.parse('http://127.0.0.1:5000/content/v1.0/contents'));
print("data!! :>> $data");
} catch (error) {
print("ERROR! $error");
}
}
it always go to catch and says Connection Refused. But when i tried to request in postman and access the url in browser, it shows the data there
I am trying to do a super simple http.get in dart with Flutter but I am not getting a result, it gets blocked.
Any idea why this happens?
Edit1: after a minute of waiting, it got to the catch the following exception:
SocketException: Failed host lookup: 'worldtimeapi.org' (OS Error: No address associated with hostname, errno = 7)
My code:
import 'package:http/http.dart' as http;
void getTime() async {
try{
var url = Uri.parse('http://worldtimeapi.org/api/timezone/Europe/London');
// var url = Uri.parse('https://catfact.ninja/fact');
final response = await http.get(url); //await causes a block forever. nothing happens afterwards
// Map data = jsonDecode(response.body);
print(response);
}catch(e){
print(e);
}
}
The problem is because of not allowing the Clear Text Traffic, which in this case is the HTTP, check this answer to get the steps for allowing it.
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.
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.