Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart Http Package request timeout

Tags:

http

flutter

dart

While using http package in my flutter app, I encountered a slight issue. I am testing on localhost and when I post something in database using http.post, it doesn't return response for default time (i.e. 60s I think) when server is not running. And when I start the apache and mysql services within the timeout, it posts the data in the server . Is there any way to reduce the timeout of the http requests in dart http package? Or is there any alternative solution?

like image 748
Zero Live Avatar asked Nov 21 '19 02:11

Zero Live


People also ask

How do you handle response timeout?

Just remove future at the end of the block. Futures, like other Scala constructs, are immutable data structures which calling methods on them will return another futures. When you call onComplete method, it returns new future with your HttpResponse .

What is HTTP timeout?

The HyperText Transfer Protocol (HTTP) 408 Request Timeout response status code means that the server would like to shut down this unused connection. It is sent on an idle connection by some servers, even without any previous request by the client.

What is HTTP client in flutter?

An HTTP client for communicating with an HTTP server. Sends HTTP requests to an HTTP server and receives responses. Maintains state, including session cookies and other cookies, between multiple requests to the same server. Note: HttpClient provides low-level HTTP functionality.


2 Answers

This is for http package

final response = await http.post(Url).timeout(Duration(seconds: 5));

And this is for Dio package (recommend to test this package)

BaseOptions options = new BaseOptions(
    baseUrl: baseUrl,
    connectTimeout: 10000, //10 seconds
    receiveTimeout: 10000,
   );

Dio dio = new Dio(options);

Response<dynamic> response = await dio.post(url, data: mapData);
like image 150
Shojaeddin Avatar answered Sep 18 '22 06:09

Shojaeddin


You have two options availabe.

Reduce the timeout on the HttpClient

final client = new HttpClient();
client.connectionTimeout = const Duration(seconds: 10);

This will apply to all request made by the same client. If the request exceeds this timeout, a SocketException is thrown.

Set a per request timeout
You can set a timeout on any Future using the Future.timeout method.

try {
  ..
  final request = await client.get(...);
  final response = await request.close().timeout(const Duration(seconds: 10));
  // more code
} on TimeoutException catch (e) {
  // handle timeout
}
like image 31
Skoff Avatar answered Sep 20 '22 06:09

Skoff