xxxxxxxxxx
import 'package:http/http.dart' as http;
// Function to make an API request
Future<void> makeApiRequest() async {
final url = 'https://api.example.com/your-endpoint';
try {
final response = await http.get(url);
if (response.statusCode == 200) {
// Request successful, handle the response
print(response.body);
} else {
// Request unsuccessful, handle the error
print('Request failed with status: ${response.statusCode}');
}
} catch (e) {
// Error occurred during the request
print('Error: $e');
}
}
xxxxxxxxxx
import 'package:http/http.dart' as http;
import 'dart:convert';
Future<void> fetchData() async {
try {
var url = Uri.parse('https://api.example.com/data');
var response = await http.get(url);
if (response.statusCode == 200) {
var data = jsonDecode(response.body);
// Process the received data as needed
print(data);
} else {
// Handle error response
print('Request failed with status: ${response.statusCode}');
}
} catch (e) {
// Handle any exceptions that occur
print('Error: $e');
}
}
xxxxxxxxxx
void getTime () async
// make the request
Response response = await get('http://worldtimeapi. org/api/timezone/Eu rope/London ') ;
Map data = jsonDecode ( response . body);
//print (data) ;
}
/*
// Response:
// PRO TIP: Use Json Viewer Plugin on Android Studio!
// https://plugins.jetbrains.com/plugin/14149-json-viewer
{
week_number: 34,
utc_offset: +01: 00,
utc_datetime: 22019-08-22T16: 46: 37.296404+00: 00,
unixtime: 1566492397,
timezone: Europe/London,
raw_offset: 0,
dst_until: 2019-10-27TO1: 00: 00+00: 00,
dst_offset: 3600,
dst_from: 2019-03-31TO1: 00: 00+00: 00,
dst: true,
day_of_year: 234,
day_of_week: 4,
datetime2019-08-22T17: 46: 37.296404+01: 00,
client_ip: 81.147.155.132,
abbreviation: BST
}
*/
xxxxxxxxxx
var client = http.Client();
try {
var uriResponse = await client.post(Uri.parse('https://example.com/whatsit/create'),
body: {'name': 'doodle', 'color': 'blue'});
print(await client.get(uriResponse.bodyFields['uri']));
} finally {
client.close();
}
xxxxxxxxxx
class UserAgentClient extends http.BaseClient {
final String userAgent;
final http.Client _inner;
UserAgentClient(this.userAgent, this._inner);
Future<http.StreamedResponse> send(http.BaseRequest request) {
request.headers['user-agent'] = userAgent;
return _inner.send(request);
}
}