Flutter http.post timeout [duplicate] - flutter

This method submits a simple HTTP request and calls a success or error callback just fine:
void _getSimpleReply( String command, callback, errorCallback ) async {
try {
HttpClientRequest request = await _myClient.get( _serverIPAddress, _serverPort, '/' );
HttpClientResponse response = await request.close();
response.transform( utf8.decoder ).listen( (onData) { callback( onData ); } );
} on SocketException catch( e ) {
errorCallback( e.toString() );
}
}
If the server isn't running, the Android-app more or less instantly calls the errorCallback.
On iOS, the errorCallback takes a very long period of time - more than 20 seconds - until any callback gets called.
May I set for HttpClient() a maximum number of seconds to wait for the server side to return a reply - if any?

There are two different ways to configure this behavior in Dart
Set a per request timeout
You can set a timeout on any Future using the Future.timeout method. This will short-circuit after the given duration has elapsed by throwing a TimeoutException.
try {
final request = await client.get(...);
final response = await request.close()
.timeout(const Duration(seconds: 2));
// rest of the code
...
} on TimeoutException catch (_) {
// A timeout occurred.
} on SocketException catch (_) {
// Other exception
}
Set a timeout on HttpClient
You can also set a timeout on the HttpClient itself using HttpClient.connectionTimeout. This will apply to all requests made by the same client, after the timeout was set. When a request exceeds this timeout, a SocketException is thrown.
final client = new HttpClient();
client.connectionTimeout = const Duration(seconds: 5);

You can use timeout
http.get(Uri.parse('url')).timeout(
const Duration(seconds: 1),
onTimeout: () {
// Time has run out, do what you wanted to do.
return http.Response('Error', 408); // Request Timeout response status code
},
);

The HttpClient.connectionTimeout didn't work for me. However, I knew that the Dio packet allows request cancellation. Then, I dig into the packet to find out how they achieve it and I adapted it to me. What I did was to create two futures:
A Future.delayed where I set the duration of the timeout.
The HTTP request.
Then, I passed the two futures to a Future.any which returns the result of the first future to complete and the results of all the other futures are discarded. Therefore, if the timeout future completes first, your connection times out and no response will arrive. You can check it out in the following code:
Future<Response> get(
String url, {
Duration timeout = Duration(seconds: 30),
}) async {
final request = Request('GET', Uri.parse(url))..followRedirects = false;
headers.forEach((key, value) {
request.headers[key] = value;
});
final Completer _completer = Completer();
/// Fake timeout by forcing the request future to complete if the duration
/// ends before the response arrives.
Future.delayed(timeout, () => _completer.complete());
final response = await Response.fromStream(await listenCancelForAsyncTask(
_completer,
Future(() {
return _getClient().send(request);
}),
));
}
Future<T> listenCancelForAsyncTask<T>(
Completer completer,
Future<T> future,
) {
/// Returns the first future of the futures list to complete. Therefore,
/// if the first future is the timeout, the http response will not arrive
/// and it is possible to handle the timeout.
return Future.any([
if (completer != null) completeFuture(completer),
future,
]);
}
Future<T> completeFuture<T>(Completer completer) async {
await completer.future;
throw TimeoutException('TimeoutError');
}

This is an example of how to extend the http.BaseClient class to support timeout and ignore the exception of the S.O. if the client's timeout is reached first.
you just need to override the "send" method...
the timeout should be passed as a parameter to the class constructor.
import 'dart:async';
import 'package:http/http.dart' as http;
// as dart does not support tuples i create an Either class
class _Either<L, R> {
final L? left;
final R? right;
_Either(this.left, this.right);
_Either.Left(L this.left) : right = null;
_Either.Right(R this.right) : left = null;
}
class TimeoutClient extends http.BaseClient {
final http.Client _httpClient;
final Duration timeout;
TimeoutClient(
{http.Client? httpClient, this.timeout = const Duration(seconds: 30)})
: _httpClient = httpClient ?? http.Client();
Future<http.StreamedResponse> send(http.BaseRequest request) async {
// wait for result between two Futures (the one that is reached first) in silent mode (no throw exception)
_Either<http.StreamedResponse, Exception> result = await Future.any([
Future.delayed(
timeout,
() => _Either.Right(
TimeoutException(
'Client connection timeout after ${timeout.inMilliseconds} ms.'),
)),
Future(() async {
try {
return _Either.Left(await _httpClient.send(request));
} on Exception catch (e) {
return _Either.Right(e);
}
})
]);
// this code is reached only for first Future response,
// the second Future is ignorated and does not reach this point
if (result.right != null) {
throw result.right!;
}
return result.left!;
}
}

Their is onError option which works fine if their is any exception like no internet.It has to return response(my case in below code) or null.
In response their are 2 options Body and Status code.
var response = await http.post(url, body: body, headers: _headers).onError(
(error, stackTrace) => http.Response(
jsonEncode({
'message':no internet please connect to internet first
}),
408));

You can also choose to override the settings for a HttpClient:
class DevHttpOverrides extends HttpOverrides {
#override
HttpClient createHttpClient(SecurityContext? context) {
return super.createHttpClient(context)
..connectionTimeout = Duration(seconds: 2);
}
}

Related

How to catch an Error for timeout on http.client Flutter

I have a Future that calls a POST API using the http.client structure.
At the moment there is an issue with said API and my call is timing out before the full header is received, giving me a unhandled exception.
How is the best way to return this exception and show a snackbar of the issue returned?
Future<dynamic> get() async {
try {
var response = await client.post(
Uri.parse(Url),
headers: headers,
body: body,
);
}
here is the simple http call to catch an Error for timeout
return the error and catch this where from you handle the api call
import 'package:http/http.dart';
Future<dynamic> get() async {
try {
var response = await post(
Uri.parse(Url),
headers: headers,
body: body,
).timeout(Duration(seconds: 2), onTimeout: (){
/// here is the response if api call time out
/// you can show snackBar here or where you handle api call
return Response('Time out!', 500);
});
}catch(e){
print(e);
}
}
you can change your duration in the timeout method

Flutter handling http timeout - closing connection

I am having hard times with figuring out how to handle exceptions and closed connections using Flutter http package https://pub.dev/packages/http.
I have setup timeout of 10 sec and want to show some response to a user within that 10 sec. There is CircularProgreseIndicator and activated by isLoading variable, with error text wrapped up in UI for better presentation.
This example below will timeout after 10 seconds, but after around 20-30 sec, app will crash with an error Connection closed before full header was received
Same error will be thrown if I use client.close() (including finally section).
I would like to control timeout time (4-5 sec) and close connection if no response is received within 5 sec. I don't want to implement automatic retry (want to use pull to refresh/retry manually etc.)
Would anyone know how to implement client.close() properly? Thx
Example:
Future<String> getData() async {
final client = http.Client();
try {
var response = await client.get(Uri.parse(endpoint)).timeout(
Duration(seconds: 10),
onTimeout: () {
// Closing client here throwns an error
// client.close(); // Connection closed before full header was received
return http.Response('Error', 500); // Replace 500 with your http code.
},
);
// Some logic for state etc.
if (response.statusCode == 200) {
this.setState(() {
data = jsonDecode(response.body);
isLoading = false;
isError = false;
});
return "success";
} else {
// Closing client here throwns an error
// client.close(); // Connection closed before full header was received
setState(() {
isLoading = false;
isError = true;
});
return "error";
}
// Finally... close connection
} finally {
// Closing client here throwns an error
// client.close(); // Connection closed before full header was received
}
}
UPDATE: (workaround)
I have found a bit different approach and app does not crash with example below. Loading will be shown all the time if there is no communication with the server (no internet connection). If server returns anything but 200 (ok), "Server error occurred" will be shown.
Future<String> getData() async {
String category = await getCategory();
String endpoint =
Endpoints().getEndpoint("apiServer") + '/categories/' + category;
final client = RetryClient(http.Client());
try {
var response = await client.get(Uri.parse(endpoint));
// Added extra loading time for better UI
await Future.delayed(const Duration(milliseconds: 700), () {});
if (response.statusCode == 200) {
this.setState(() {
data = jsonDecode(response.body);
isLoading = false;
});
showSnackbar("success", "Category list retreived");
return "success";
} else {
// client.close(); // Connection closed before full header was received
setState(() {
isLoading = false;
isError = true;
});
showSnackbar("error", "Server error occurred. Try again");
return "error";
}
} finally {
client.close();
}
}

Why sending the following request ends up with uncaught exception?

I have the following Flutter & Dart code function, which sends a request to the server:
Future<void> autoAuth(BuildContext ctx) async {
final url = Uri.parse('${this._baseURL.toString()}/auto-auth');
try {
final deviceStorage = await SharedPreferences.getInstance();
if (deviceStorage.getString('refreshToken') == null) {
return this._setUser(null);
}
final response = await http.post(url, headers: {
'Authorization': 'Bearer ${deviceStorage.getString('refreshToken')!}',
}).timeout(const Duration(seconds: 3));
final Map<String, dynamic> responseBody = json.decode(response.body);
if (responseBody['success']) {
this._refreshAccessToken(ctx, deviceStorage);
return this._setUser(new User(
id: responseBody['data']['id'],
isSubscribed: responseBody['data']['isSubscribed'],
playlistId: responseBody['data']['playlistId'],
));
}
this._setUser(null);
} on SocketException {
this._setUser(null);
throw Error();
} on TimeoutException {
this._setUser(null);
throw Error();
} catch (_) {
this._setUser(null);
}
}
Note, that url is wrong intentionally, so the request will timeout.
But, for this, I coded: .timeout(...) on the future request. So, basically, after 3 secnods it should caught by on TimeoutException exception catch.
It does so. However, after something like 1 minute (probably some default timeout of http request in dart), I get an uncaught exception because the request has timed-out. Where Am I wrong?
This is because you are using it in the wrong way. The .timeout code you use, is generic timeout for any future. Thus, you catch the error of the future timeout, but you don't catch the error being generated from the http request timeout.
To use it correctly, first add the following import: import 'package:http/io_client.dart' as http;
Then change the code to:
final ioClient = HttpClient();
ioClient.connectionTimeout = const Duration(seconds: 3);
final client = http.IOClient(ioClient);
final response = await client.post(url, headers: {
'Authorization': 'Bearer ${deviceStorage.getString('refreshToken')!}',
});

Retry Http Get request if there is no response in Flutter

getData() async {
http.Response response = await http.get('https://www.example.com/);
print(response.body);
}
The above function works to get the HTML code of a page but it fails in some cases. The function is sometimes never completed and it waits forever to get response( For example, if the app is opened while internet is off and even when its turned on, it never connects). In such situations is there any way to retry ?
I tried the http retry package but it gives me 15+ errors.
Example code for how this could be done:
import 'package:http/http.dart' as http;
import 'dart:convert';
Future<List> loadData() async {
bool loadRemoteDatatSucceed = false;
var data;
try {
http.Response response = await http.post("https://www.example.com",
body: <String, String>{"username": "test"});
data = json.decode(response.body);
if (data.containsKey("success")) {
loadRemoteDatatSucceed = true;
}
} catch (e) {
if (loadRemoteDatatSucceed == false) retryFuture(loadData, 2000);
}
return data;
}
retryFuture(future, delay) {
Future.delayed(Duration(milliseconds: delay), () {
future();
});
}
You can use RetryPolicy from http package to retry your connection, just create your own class and inherit form RetryPolicy and override these function like the following example, then create a Client using HttpClientWithInterceptor.build and add your custom retryPolicy as a parameter, this will retry your request for a number of times until a condition is met, if not, it'll just stop retrying.
import 'package:http/http.dart';
class MyRetryPolicy extends RetryPolicy {
final url = 'https://www.example.com/';
#override
// how many times you want to retry your request.
int maxRetryAttempts = 5;
#override
Future<bool> shouldAttemptRetryOnResponse(ResponseData response) async {
//You can check if you got your response after certain timeout,
//or if you want to retry your request based on the status code,
//usually this is used for refreshing your expired token but you can check for what ever you want
//your should write a condition here so it won't execute this code on every request
//for example if(response == null)
// a very basic solution is that you can check
// for internet connection, for example
try {
final result = await InternetAddress.lookup('google.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
return true;
}
return false;
} on SocketException catch (_) {
return false;
}
}
}
then create and use a client to make your requests.
it will automatically retry the request if the condition you wrote is met.
Client client = HttpClientWithInterceptor.build(
retryPolicy: ExpiredTokenRetryPolicy(),
);
final response = await client.get('https://www.example.com/);
there is also a package to check for internet connection if that your problem, see connectivity
You can use try-catch blocks inside async functions like you would in synchronous code. Perhaps you'd be able to add some sort of error handling mechanism in the function, and retry the function on error? Here's some documentation on that one.
Example from the docs:
try {
var order = await getUserOrder();
print('Awaiting user order...');
} catch (err) {
print('Caught error: $err');
}
You can also catch specific Exceptions, per this github issue.
doLogin(String username, String password) async {
try {
var user = await api.login(username, password);
_view.onLoginSuccess(user);
} on Exception catch(error) {
_view.onLoginError(error.toString());
}
}
EDIT: This may also help.
While we're at it, look here for a function that reattempts an async operation however many times you need.

rxDart not calling onError

I am trying to make a simple request to backend using rxDart. But the problem I face is that when I get a http error such as 404, onError is not called, however, it is possible to extract it in onData.
I have a little experience with RxJava + retrofit and there it works as expected, when there is a response with error http status code onError is called and can be handled appropriately.
1. What am I doing wrong, or is it intended behavior?.
Object sendProfileData() {
Stream<Response> stream = onboardingRepository.createUser(User(name: 'name', surname: 'surname', lat: 1.0, lng: 2.0));
stream.listen((response) {
print(response.statusCode);
setAttributes();
}, onError: (e) {
print(e);
});
}
OnboardingRepository.dart:
class OnboardingRepository {
Observable<Response> createUser(User user) {
return Observable.fromFuture(TMApi.createUser(user));
}
}
TMApi.dart:
class TMApi {
static Future<http.Response> createUser(User user) async {
String url = '$baseUrl/create_user';
return await http.post(url, body: json.encode(user.toJson()));
}
}
What would be the best way to handle the event in the View? There should be an error displayed if error occurs, otherwise it should open a new screen. sendProfileData() method will return an Object, based on that I am going to perform actions in the view, but that doesn't sound like a very elegant solution...
Any suggestions on architecture are welcome :)
the http library in dart works a bit different than Retrofit.
The Future returned by http.post only throws an exception when there is an io error (socket error, no internet).
Server responses like 404 are reflected in the http.Response.
I created a simple convenience method that might help you:
void throwIfNoSuccess(http.Response response) {
if(response.statusCode < 200 || response.statusCode > 299) {
print('http error!');
print(response.body);
throw new HttpException(response);
}
}
class HttpException implements Exception {
HttpException(this.response);
http.Response response;
}
How to use:
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<UserProfile> getUserProfile(String userId) async {
final url = 'https://example.com/api/users/$userId';
final response = await http.get(url);
throwIfNoSuccess(response);
final jsonBody = json.decode(response.body);
return UserProfile.fromJson(jsonBody);
}