connect method

  1. @override
Future<void> connect()
override

Establishes a connection to the resource referenced by this UrlConnection.

Must be implemented by subclasses to perform protocol-specific logic (e.g., building a HttpClientRequest, sending the request, and receiving the response).

Throws a NetworkException if any error occurs during the connection process.

Implementation

@override
Future<void> connect() async {
  if (_connected) return;

  final client = HttpClient();
  try {
    final request = await client.getUrl(url.toUri());
    _setRequest(request);
    final response = await request.close();
    _setResponse(response);
  } on SocketException catch (e) {
    throw NetworkException(
      'Failed to connect to ${url.toString()}: ${e.message}',
      cause: e
    );
  } on HandshakeException catch (e) {
    throw NetworkException(
      'SSL/TLS handshake failed for ${url.toString()}: ${e.message}',
      cause: e
    );
  } on HttpException catch (e) {
    throw NetworkException(
      'HTTP error for ${url.toString()}: ${e.message}',
      cause: e
    );
  } catch (e) {
    throw NetworkException(
      'An unknown network error occurred for ${url.toString()}: $e',
      cause: e
    );
  } finally {
    client.close(); // Ensure the client is closed
  }
}