The dart:io
library provides classes that command-line apps can use for accessing HTTP resources, as well as running HTTP servers.
The following are class mainly used in writing HTTP clients & servers.
The HttpClient class helps you connect to HTTP resources.
Note:
HttpClient only works with Dart command-line and Server-side application.
The HttpClient class does not work in browser-based apps. When programming in the browser, use the dart:html
HttpRequest
class.
To use the HttpClient
you must import it, dart:io
library.
import 'dart:io';
The following code snippet shows how to connect with http resources.
import 'dart:io';
import 'dart:convert';
Future main() async {
var url = Uri.parse('http://localhost:8080');
var httpClient = HttpClient();
var request = await httpClient.getUrl(url);
var response = await request.close();
var data = await utf8.decoder.bind(response).toList();
print('Response ${response.statusCode}: $data');
httpClient.close();
}
The HttpServer class provides the low-level functionality for building web servers.
To use the HttpServer
you must import it, dart:io
library.
import 'dart:io';
The following sample web server returns simple text information.
8080
and address 127.0.0.1
(localhost)./
.import 'dart:io';
void processRequest(HttpRequest request) {
final response = request.response;
if (request.uri.path == '/') {
response
..headers.contentType = ContentType(
'text',
'plain',
)
..write('Hello from the server');
} else {
response.statusCode = HttpStatus.notFound;
}
response.close();
}
Future main() async {
final requests = await HttpServer.bind('localhost', 8080);
print('Server running: http://localhost:8080');
await for (var request in requests) {
processRequest(request);
}
}
Run: <http://localhost:8080>