Created
August 4, 2019 18:54
-
-
Save nemethmik/4d4ec76085e58a62c9eab17a884f0c80 to your computer and use it in GitHub Desktop.
How to use Dart's low level HttpClient with timeout and getting back the response text from the HttpClientResponse stream
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:test/test.dart'; | |
import 'dart:async'; | |
import 'dart:io'; | |
import 'dart:convert'; | |
void main() { | |
group("B1SL_LoginTestSeries", () { | |
const ipAddress = "http://hana93srv:50001"; | |
const url = "/b1s/v1/"; | |
const user = "manager"; | |
const pwd ="123qwe"; | |
const companyDB ="SBODEMOUS"; | |
test("Login with HTTPClient",() async { | |
try { | |
final String postBody = '{"UserName":"${user}", "Password":"${pwd}", "CompanyDB":"${companyDB}"}'; | |
final String queryUrl = ipAddress + url + "Login"; | |
//final String queryUrl = "http://192.168.250.92:50001" + url + "Login"; | |
final HttpClient client = HttpClient()..connectionTimeout = Duration(seconds: 15); | |
final HttpClientRequest request = await client.postUrl(Uri.parse(queryUrl)); | |
request.write(postBody); | |
final HttpClientResponse response = await request.close(); | |
dynamic responseBodyText = await _getResponseBody(response); | |
print(responseBodyText); | |
expect(responseBodyText, isNotNull); | |
expect(responseBodyText.isNotEmpty, isTrue); | |
} catch(error,stackTrace) { | |
print(error); | |
print(stackTrace); | |
expect(error,isNull); | |
} | |
}); | |
}); | |
} | |
Future<dynamic> _getResponseBody(HttpClientResponse response) { | |
StringBuffer responseBody = StringBuffer(); | |
Completer completer = Completer(); | |
response.transform(utf8.decoder).listen((String onData){ | |
responseBody.write(onData); | |
}, onDone: ()=> completer.complete(responseBody.toString())); | |
return completer.future; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've spent a number of hours to experiment with using the brutally low level HttpClient and HttpClientResponse classes of dart:io just to be able to set timeout on my HTTP communication. Actually, connectionTimeout works, but instead of throwing a nice SocketException we get a NoSuchMethodError, possibly because of a bug in dart.io. The other option is to use Future's timeout, but I wasn't sure, if it may cause memory/resource leaks? The worst case would be that after a minute or so the network layer anyway kills the connection. So, I think Future timeout is the way to go, it is so clean and dead simple.