You need to sign in or sign up before continuing.
http.dart 10.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
import 'dart:async';
import 'dart:convert';

import 'package:flutter/foundation.dart';

import '../src/certificates/certificates.dart';
import '../src/exceptions/exceptions.dart';
import '../src/http_impl/http_request_stub.dart'
    if (dart.library.html) 'http_impl/http_request_html.dart'
    if (dart.library.io) 'http_impl/http_request_io.dart';
import '../src/http_impl/request_base.dart';
import '../src/multipart/form_data.dart';
import '../src/request/request.dart';
import '../src/response/response.dart';
import '../src/status/http_status.dart';
import 'interceptors/get_modifiers.dart';

typedef Decoder<T> = T Function(dynamic data);

class GetHttpClient {
  String userAgent;
  String baseUrl;

  String defaultContentType = 'application/json; charset=utf-8';

  bool followRedirects;
  int maxRedirects;
  int maxAuthRetries;

  Decoder defaultDecoder;

  Duration timeout;

  bool errorSafety = true;

  final HttpRequestBase _httpClient;

  final GetModifier _modifier;

  GetHttpClient({
    this.userAgent = 'getx-client',
    this.timeout = const Duration(seconds: 8),
    this.followRedirects = true,
    this.maxRedirects = 5,
    this.maxAuthRetries = 1,
    bool allowAutoSignedCert = false,
    this.baseUrl,
    List<TrustedCertificate> trustedCertificates,
  })  : _httpClient = HttpRequestImpl(
          allowAutoSignedCert: allowAutoSignedCert,
          trustedCertificates: trustedCertificates,
        ),
        _modifier = GetModifier();

  void addAuthenticator<T>(RequestModifier<T> auth) {
    _modifier.authenticator = auth as RequestModifier;
  }

  void addRequestModifier<T>(RequestModifier<T> interceptor) {
    _modifier.addRequestModifier<T>(interceptor);
  }

  void removeRequestModifier<T>(RequestModifier<T> interceptor) {
    _modifier.removeRequestModifier(interceptor);
  }

  void addResponseModifier<T>(ResponseModifier<T> interceptor) {
    _modifier.addResponseModifier(interceptor);
  }

  void removeResponseModifier<T>(ResponseModifier<T> interceptor) {
    _modifier.removeResponseModifier<T>(interceptor);
  }

  Uri _createUri(String url, Map<String, dynamic> query) {
    if (baseUrl != null) {
      url = baseUrl + url;
    }
    final uri = Uri.parse(url);
    if (query != null) {
      uri.replace(queryParameters: query);
    }
    return uri;
  }

  Future<Request<T>> _requestWithBody<T>(
    String url,
    String contentType,
    dynamic body,
    String method,
    Map<String, dynamic> query,
    Decoder<T> decoder,
  ) async {
    assert(method != null);
    assert(body != null);

    List<int> bodyBytes;

    if (body is FormData) {
      bodyBytes = await body.toBytes();
    } else {
      try {
        var jsonString = json.encode(body);

        //TODO check this implementation
        if (contentType != null) {
          if (contentType.toLowerCase() ==
              'application/x-www-form-urlencoded') {
            var paramName = 'param';
            jsonString = '$paramName=${Uri.encodeQueryComponent(jsonString)}';
          }
        }

        bodyBytes = utf8.encode(jsonString);
      } on Exception catch (err) {
        if (!errorSafety) {
          throw UnexpectedFormat(err.toString());
        } else {}
      }
    }

    final bodyStream = BodyBytes.fromBytes(bodyBytes);

    final headers = <String, String>{};

    _setHeadersWithBody(contentType, headers, bodyBytes);

    final uri = _createUri(url, query);

    return Request(
      method: method,
      url: uri,
      headers: headers,
      bodyBytes: bodyStream,
      followRedirects: followRedirects,
      maxRedirects: maxRedirects,
    );
  }

  void _setHeadersWithBody(
    String contentType,
    // String jsonString,
    Map<String, String> headers,
    List<int> bodyBytes,
    // List<MultipartFile> files,
  ) {
    // if (files != null) {
    //   headers['content-type'] = 'multipart/form-data';
    //   headers['x-requested-with'] = 'XMLHttpRequest';
    // } else {
    //   headers['content-type'] = contentType ?? defaultContentType;
    // }

    headers['content-type'] =
        contentType ?? defaultContentType; // verify if this is better location

    headers['user-agent'] = userAgent;
    headers['content-length'] = bodyBytes.length.toString();
  }

  void _setSimpleHeaders(
    Map<String, String> headers,
    String contentType,
  ) {
    headers['content-type'] = contentType ?? defaultContentType;
    headers['user-agent'] = userAgent;
  }

  Future<Response<T>> _performRequest<T>(
    HandlerExecute<T> handler, {
    bool authenticate = false,
    int requestNumber = 1,
    Map<String, String> headers,
  }) async {
    try {
      var request = await handler();

      headers?.forEach((key, value) {
        request.headers[key] = value;
      });

      if (authenticate) await _modifier.authenticator(request);
      await _modifier.modifyRequest(request);

      var response = await _httpClient.send<T>(request);

      await _modifier.modifyResponse(request, response);

      if (HttpStatus.unauthorized == response.statusCode &&
          _modifier.authenticator != null &&
          requestNumber <= maxAuthRetries) {
        return _performRequest(
          handler,
          authenticate: true,
          requestNumber: requestNumber + 1,
          headers: request.headers,
        );
      } else if (HttpStatus.unauthorized == response.statusCode) {
        if (!errorSafety) {
          throw UnauthorizedException();
        } else {
          return Response<T>(
            request: request,
            headers: response.headers,
            statusCode: response.statusCode,
            body: response.body,
            statusText: response.statusText,
          );
        }
      }

      return response;
    } on Exception catch (err) {
      if (!errorSafety) {
        throw GetHttpException(err.toString());
      } else {
        return Response<T>(
          request: null,
          headers: null,
          statusCode: null,
          body: null,
          statusText: "$err",
        );
      }
    }
  }

  Future<Request<T>> _get<T>(
    String url,
    String contentType,
    Map<String, dynamic> query,
    Decoder<T> decoder,
  ) {
    final headers = <String, String>{};
    _setSimpleHeaders(headers, contentType);
    final uri = _createUri(url, query);

    return Future.value(Request<T>(
      method: 'get',
      url: uri,
      headers: headers,
      decoder: decoder ?? (defaultDecoder as Decoder<T>),
    ));
  }

  Future<Request<T>> _post<T>(
    String url, {
    String contentType,
    @required dynamic body,
    Map<String, dynamic> query,
    Decoder<T> decoder,
    // List<MultipartFile> files,
  }) {
    assert(body != null);
    return _requestWithBody<T>(
      url,
      contentType,
      body,
      'post',
      query,
      decoder,
    );
  }

  Future<Request<T>> _put<T>(
    String url, {
    String contentType,
    @required dynamic body,
    @required Map<String, dynamic> query,
    Decoder<T> decoder,
    //  List<MultipartFile> files,
  }) {
    assert(body != null);
    return _requestWithBody(url, contentType, body, 'put', query, decoder);
  }

  Request<T> _delete<T>(
    String url,
    String contentType,
    Map<String, dynamic> query,
    Decoder<T> decoder,
  ) {
    final headers = <String, String>{};
    _setSimpleHeaders(headers, contentType);
    final uri = _createUri(url, query);

    return Request<T>(
        method: 'delete', url: uri, headers: headers, decoder: decoder);
  }

  Future<Response<T>> post<T>(
    String url,
    dynamic body, {
    String contentType,
    Map<String, String> headers,
    Map<String, dynamic> query,
    Decoder<T> decoder,
    // List<MultipartFile> files,
  }) async {
    try {
      var response = await _performRequest<T>(
        () => _post<T>(
          url,
          contentType: contentType,
          body: body,
          query: query,
          decoder: decoder,
          //  files: files,
        ),
        headers: headers,
      );
      return response;
    } on Exception catch (e) {
      if (!errorSafety) {
        throw GetHttpException(e.toString());
      }
      return Future.value(Response<T>(
        request: null,
        statusCode: null,
        body: null,
        statusText: 'Can not connect to server. Reason: $e',
      ));
    }
  }

  Future<Response<T>> put<T>(
    String url,
    Map<String, dynamic> body, {
    String contentType,
    Map<String, String> headers,
    Map<String, dynamic> query,
    Decoder<T> decoder,
  }) async {
    try {
      var response = await _performRequest(
        () => _put(
          url,
          contentType: contentType,
          query: query,
          body: body,
          decoder: decoder,
        ),
        headers: headers,
      );
      return response;
    } on Exception catch (e) {
      if (!errorSafety) {
        throw GetHttpException(e.toString());
      }
      return Future.value(Response<T>(
        request: null,
        statusCode: null,
        body: null,
        statusText: 'Can not connect to server. Reason: $e',
      ));
    }
  }

  Future<Response<T>> get<T>(
    String url, {
    Map<String, String> headers,
    String contentType,
    Map<String, dynamic> query,
    Decoder<T> decoder,
  }) async {
    try {
      var response = await _performRequest<T>(
        () => _get<T>(url, contentType, query, decoder),
        headers: headers,
      );
      return response;
    } on Exception catch (e) {
      if (!errorSafety) {
        throw GetHttpException(e.toString());
      }
      return Future.value(Response<T>(
        request: null,
        statusCode: null,
        body: null,
        statusText: 'Can not connect to server. Reason: $e',
      ));
    }
  }

  Future<Response<T>> delete<T>(
    String url, {
    Map<String, String> headers,
    String contentType,
    Map<String, dynamic> query,
    Decoder<T> decoder,
  }) async {
    try {
      var response = await _performRequest(
        () async => _delete<T>(url, contentType, query, decoder),
        headers: headers,
      );
      return response;
    } on Exception catch (e) {
      if (!errorSafety) {
        throw GetHttpException(e.toString());
      }
      return Future.value(Response<T>(
        request: null,
        statusCode: null,
        body: null,
        statusText: 'Can not connect to server. Reason: $e',
      ));
    }
  }

  void close() {
    _httpClient.close();
  }
}