dart - http.get not returning a response for HTTP URL - flutter

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.

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.

Flutter Http request avaible on broser but can't work on Android device

[Solved] It's caused by my own network situation.If you are in China , don't forget to check your VPN.
I want to use TheMovieDB api in my flutter project, but I can't get the response when I run it on my Android device.
when I try to run it in browser , it works perfectly.
just few minutes ago it works. But then it doesn't.
My code:
final url = "https://api.themoviedb.org/3/movie/popular?api_key=3c4cb870e3f3c729ef1eb2d0538ba4f7&language=en-US?page=$page";
try{
var response = await http.get(Uri.parse(url));
print(response);
if (response.statusCode == 200) {
var json = convert.jsonDecode(response.body) as Map<String, dynamic>;
print('json is:');
print(json);
result = json['results'];
} else {
result =
'Error getting IP address:\nHttp status ${response.statusCode}';
}
}catch(e){
print(e);
}
the error message is:
SocketException: OS Error: Connection timed out, errno = 110, address = api.themoviedb.org, port = 42230
Please check if you have provided the correct permissions and also if you have specified the right config on your emulator

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.

How to get Public IP in Flutter?

In my case, i need public IP Address. But, after research almost all documentary related to Local IP like: Get_IP, I want something like 202.xxx not 192.168.xxx. Can someone give some advice?
As far as I'm aware, there's no way to get the public IP of a device from within that device. This is because the vast majority of the time, the device doesn't know it's own public IP. The public IP is assigned to the device from the ISP, and your device is usually separated from the ISP through any number of modems, routers, switches, etc.
You need to query some external resource or API (such as ipify.org) that will then tell you what your public IP is. You can do this with a simple HTTP request.
import 'package:http/http.dart';
Future<String> getPublicIP() async {
try {
const url = 'https://api.ipify.org';
var response = await http.get(url);
if (response.statusCode == 200) {
// The response body is the IP in plain text, so just
// return it as-is.
return response.body;
} else {
// The request failed with a non-200 code
// The ipify.org API has a lot of guaranteed uptime
// promises, so this shouldn't ever actually happen.
print(response.statusCode);
print(response.body);
return null;
}
} catch (e) {
// Request failed due to an error, most likely because
// the phone isn't connected to the internet.
print(e);
return null;
}
}
EDIT: There is now a Dart package for getting public IP information from the IPify service. You can use this package in place of the above manual solution:
import 'package:dart_ipify/dart_ipify.dart';
void main() async {
final ipv4 = await Ipify.ipv4();
print(ipv4); // 98.207.254.136
final ipv6 = await Ipify.ipv64();
print(ipv6); // 98.207.254.136 or 2a00:1450:400f:80d::200e
final ipv4json = await Ipify.ipv64(format: Format.JSON);
print(ipv4json); //{"ip":"98.207.254.136"} or {"ip":"2a00:1450:400f:80d::200e"}
// The response type can be text, json or jsonp
}
I recently came across this package dart_ipify that can do this work.
https://pub.dev/packages/dart_ipify
Here is an example:
import 'package:dart_ipify/dart_ipify.dart';
void main() async {
final ipv6 = await Ipify.ipv64();
print(ipv6); // 98.207.254.136 or 2a00:1450:400f:80d::200e
}
I came across this topic recently.
After investigating the issue, I found a solution using an external API.
I am using ipstack, it has a generous free tier.
Request a free access key
Make the following POST call
http://api.ipstack.com/check?access_key=YOUR_ACCESS_KEY
You can extract the ip parameter from the response