I started off by trying to use HTTPRequest in dart:html
but quickly realised that this is not possible in a console application. I have done some Google searching but can't find what I am after (only finding HTTP Server), is there a method of sending a normal HTTP request via a console application?
Or would I have to go the method of using the sockets and implement my own HTTP request?
There's an HttpClient class in the IO library for making HTTP requests:
import 'dart:io';
void main() {
HttpClient client = new HttpClient();
client.getUrl(Uri.parse("http://www.dartlang.org/"))
.then((HttpClientRequest request) {
return request.close();
})
.then(HttpBodyHandler.processResponse)
.then((HttpClientResponseBody body) {
print(body.body);
});
}
Update: Since HttpClient is fairly low-level and a bit clunky for something simple like this, the core Dart team has also made a pub
package, http
, which simplifies things:
import 'package:http/http.dart' as http;
void main() {
http.get('http://pub.dartlang.org/').then((response) {
print(response.body);
});
}
I found that the crypto
package was a dependency, so my pubspec.yaml
looks like this:
name: app-name
dependencies:
http: any
crypto: any
You'll be looking for the HttpClient which is part of the server side dart:io
SDK library.
Example taken from the API doc linked to above:
HttpClient client = new HttpClient();
client.getUrl(Uri.parse("http://www.example.com/"))
.then((HttpClientRequest request) {
// Prepare the request then call close on it to send it.
return request.close();
})
.then((HttpClientResponse response) {
// Process the response.
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With