openHttp method
Future<void>
openHttp({
- String method = 'GET',
- required Uri uri,
- ContentType? contentType,
- void onRequest(
- HttpClientRequest request
- void onResponse(
- HttpClientResponse response
Loads content using HTTP client.
Throws StateError if called inside a browser.
Example
import 'dart:io' show Cookie;
import 'package:universal_html/controller.dart';
Future main() async {
// Load a document.
final controller = WindowController();
controller.defaultHttpClient.userAgent = 'My Hacker News client';
await controller.openHttp(
method: 'GET',
uri: Uri.parse("https://news.ycombinator.com/"),
onRequest: (HttpClientRequest request) {
// Add custom headers
request.headers.set('Authorization', 'headerValue');
request.cookies.add(Cookie('cookieName', 'cookieValue'));
},
onResponse: (HttpClientResponse response) {
print('Status code: ${response.statusCode}');
},
);
// Select the top story using a CSS query
final titleElements = controller.document.querySelectorAll(".athing > .title");
final topStoryTitle = titleElements.first.text;
// Print result
print("Top Hacker News story is: $topStoryTitle");
}
}
Implementation
Future<void> openHttp({
String method = 'GET',
required Uri uri,
ContentType? contentType,
void Function(HttpClientRequest request)? onRequest,
void Function(HttpClientResponse response)? onResponse,
}) async {
if (isTopLevelWindowInsideBrowser) {
throw StateError('Failed to mutate the main window inside a browser');
}
// Write HTTP request.
final client = onChooseHttpClient(uri);
final request = await client.openUrl(method, uri);
if (onRequest != null) {
onRequest(request);
}
if (contentType != null) {
request.headers.contentType = contentType;
}
// Read HTTP response.
final response = await request.close();
final future = utf8.decodeStream(response);
if (onResponse != null) {
onResponse(response);
}
final content = await future;
return openContent(content, contentType: response.headers.contentType);
}