generateShortenURL method

Future<BitlyModel> generateShortenURL({
  1. required String longUrl,
  2. String? groupId,
  3. String? domain = 'bit.ly',
})

Generate shorten URL

@param longUrl url that you want to generate shorten

Example

try {
      FShort.instance
          .generateShortenURL(longUrl: 'https://www.google.com.vn/')
          .then((value) {
        setState(() {
          _shortenURL = value.link;
        });
      });
    } on BitlyException catch (_) {

    } on Exception catch (_) {

    }

Implementation

Future<BitlyModel> generateShortenURL({
  required String longUrl,
  String? groupId,
  String? domain = 'bit.ly',
}) async {
  final client = HttpClient();
  final endPoint = Uri.https('api-ssl.bitly.com', '/v4/shorten');

  final response = await client.postUrl(endPoint).then((request) {
    request.headers
      ..set(HttpHeaders.contentTypeHeader, 'application/json')
      ..set(HttpHeaders.authorizationHeader, 'Bearer $_token');

    final body = {
      'long_url': longUrl,
      'domain': domain,
      'group_guid': groupId,
    };
    request.add(utf8.encode(json.encode(body)));
    return request.close();
  });

  final responseBody = await response.transform(utf8.decoder).join();

  if (response.statusCode == StatusCode.SUCCESS ||
      response.statusCode == StatusCode.CREATED) {
    return BitlyModel.fromJson(json.decode(responseBody));
  } else {
    throw BitlyException.fromJson(json.decode(responseBody));
  }
}