Skip to content

Instantly share code, notes, and snippets.

@Headmast
Last active October 20, 2020 06:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Headmast/7b9c77fd087c47041ef62b523e50c2d8 to your computer and use it in GitHub Desktop.
Save Headmast/7b9c77fd087c47041ef62b523e50c2d8 to your computer and use it in GitHub Desktop.
import 'package:http/http.dart' as http;
import 'dart:io';
void main(List<String> arguments) async {
try {
var resp = await fetchJson(url:'https://jsonplaceholder.typicode.com/posts');
fetchJson(url:'https://i.pinimg.com/564x/e6/57/1a/e6571a6c62fb2615c741a8fcf32aef49.jpg');
print('Print json \n${resp.body}');
} catch (e) {
print("Load error: $e");
}
// How catch Unhandled exception: in Future?
fetchJson(url:'https://jsonplaceholder.typicode.com/postss')
.catchError((onError){
print("Load error: $onError");
});
}
Future<http.Response> fetchJson({String url}) async {
var startTime = DateTime.now();
print('$url \nStart time $startTime');
var resp = await http.get(url);
if (resp.statusCode != 200) {
throw Exception('Http status code ${resp.statusCode}');
}
var endTime = DateTime.now();
Duration difference = endTime.difference(startTime);
print('$url \nTime load $difference');
print('$url \nFile size in bytes ${resp.contentLength}');
return resp;
}
@vlad-bel
Copy link

vlad-bel commented Oct 20, 2020

Наверное я недостаточно описал тз для домашки. После проверки допишу задание.
1)По загрузке текста ок. Хотя я имел ввиду сделать загрузку текста через извлечение массива байтов из запроса.
Можете ознакомиться с решением в этом треде
https://stackoverflow.com/questions/19662085/read-data-content-from-an-url-in-a-main-with-dart
2) Не увидел загрузки изображения. Вот пример того как это можно сделать(что-то не нашел в сети, но он там есть!)

Future<File> getImageFromWeb(String url) {
  var client = HttpClient();
  var _downloadData = <int>[];
  var fileSave = File('./image.png');
  return client.getUrl(Uri.parse(url)).then((HttpClientRequest request) {
    return request.close();
  }).then((HttpClientResponse response) async {
    return response.first.then((value) {
      _downloadData.addAll(value);
      return fileSave.writeAsBytes(_downloadData);
    });
  });
}```

Доделайте решение и будет зачет

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment