How can i add headers for authorization and content-type flutter - flutter

i have this code for to call api;
how can I add authorization and content-type headers to this?
final url = Uri.parse('https://api.collectapi.com/economy/hisseSenedi');
var counter;
var hisseResult;
Future callHisse() async {
try{
final response = await http.get(url);
if(response.statusCode == 200){
var result = hisselistFromJson(response.body);
if(mounted);
setState(() {
counter = result.data.length;
hisseResult = result;
});
return result;
} else {
print(response.statusCode);
}
} catch(e) {
print(e.toString());
}
}
Thanks for your help

you can do this:
Map<String, String> requestHeaders = {
'Content-type': 'application/json',
'Authorization': '<Your token>'
};
final response = await http.get(url,headers:requestHeaders);

Related

Http listening to upload progress Flutter Web

I was trying to listen to the upload progress using StreamedRequest and wanted to show the upload progress in UI by listening to bytes sent, but for some reason, it doesn't seem to work. The file is being picked with the file picker package and the selected file is in binary format (Unit8List). Here's the code:
final sha1OfFileData = sha1.convert(fileData);
try {
final request = http.StreamedRequest('POST', Uri.parse(data['uploadUrl']));
request.headers.addAll({
'Authorization': data['authorizationToken'],
'Content-Type': "application/octet-stream",
'X-Bz-File-Name': fileName,
'X-Bz-Content-Sha1': sha1OfFileData.toString(),
'X-Bz-Server-Side-Encryption': 'AES256',
});
request.sink.add(fileData);
final streamedResponse = await request.send();
var received = 0;
var total = streamedResponse.contentLength ?? -1;
streamedResponse.stream.listen(
(List<int> chunk) {
received += chunk.length;
if (total == -1) {
print('Received $received bytes');
} else {
final progress = received / total;
print('Upload progress: ${(progress * 100).toStringAsFixed(2)}%');
}
},
onDone: () async {
final responseBytes = await streamedResponse.stream.toBytes();
final responseString = utf8.decode(responseBytes);
response = jsonDecode(responseString);
print(response);
},
onError: (error) {
print('Error uploading file: $error');
},
cancelOnError: true,
);
} catch (e) {
print(e);
}
However if I upload it with the normal request, it works, here's that code:
final sha1OfFileData = sha1.convert(fileData);
var response;
try {
final request = http.Request('POST', Uri.parse(data['uploadUrl']));
request.headers.addAll({
'Authorization': data['authorizationToken'],
'Content-Type': "application/octet-stream",
'X-Bz-File-Name': fileName,
'X-Bz-Content-Sha1': sha1OfFileData.toString(),
'X-Bz-Server-Side-Encryption': 'AES256',
});
request.bodyBytes = fileData;
final streamedResponse = await request.send();
final responseBytes = await streamedResponse.stream.toBytes();
final responseString = utf8.decode(responseBytes);
response = jsonDecode(responseString);
print(response);
} catch (e) {
print(e);
}

Retrieving data from http web call in flutter into a list object always empty

List is always empty even though body has contents. I am new to flutter so bare with me if this is basic. I am wanting to get back a list of station data I am coming from a c# background so forgive me if am missing something simple the test string body has the items and can see the items when i debug
class HttpService {
final String url = "url hidden";
final String host = 'url hidden';
final String apiSegment = "api/";
// ignore: non_constant_identifier_names
void login(email, password) async {
try {
Map<String, String> body = {
'username': email,
'password': password,
};
Map<String, String> headers = {'Content-Type': 'application/json'};
final msg = jsonEncode(body);
Response response =
await post(Uri.parse("$url/Login"), headers: headers, body: msg);
if (response.statusCode == 200) {
var data = jsonDecode(response.body.toString());
print(data['jwtToken']);
print('Login successfully');
final prefs = await SharedPreferences.getInstance();
await prefs.setString('jwtToken', data['jwtToken']);
List<Stations> stationData = await getStationData('11');
var test = stationData;
} else {
print('failed');
}
} catch (e) {
print(e.toString());
}
}
Future<List<Stations>> getStationData(String stationId) async {
final prefs = await SharedPreferences.getInstance();
final String? token = prefs.getString('jwtToken');
const String path = 'Station/GetAllStationData';
final uri = Uri.parse('$url/api/$path')
.replace(queryParameters: {'stationId': stationId});
List<Stations> stationData = <Stations>[];
try {
Response res = await get(uri, headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
// 'Authorization': 'Bearer $token',
});
if (res.statusCode == 200) {
var body = jsonDecode(res.body);
var body2 = body.toString();
stationData = body
.map(
(dynamic item) => Stations.fromJson(item),
)
.toList();
} else {
throw "Unable to retrieve posts.";
}
} catch (e) {
print(e.toString());
}
return stationData;
}
}
I am calling my function from the same class
List<Stations> stationData = await getStationData('11');
Data from body
Actually the problem is you are returning the data after the end of try catch.
Try this
Future<List<Stations>> getStationData(String stationId) async {
final prefs = await SharedPreferences.getInstance();
final String? token = prefs.getString('jwtToken');
const String path = 'Station/GetAllStationData';
final uri = Uri.parse('$url/api/$path')
.replace(queryParameters: {'stationId': stationId});
try {
Response res = await get(uri, headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
// 'Authorization': 'Bearer $token',
});
if (res.statusCode == 200) {
var body = jsonDecode(res.body);
final stationData = List<Stations>.from(body.map((item) => Stations.fromJson(item))); // made some changes
return stationData;
} else {
throw "Unable to retrieve posts.";
}
} catch (e) {
rethrow;
}
}
I hope this will help you

Flutter upload image

Get Api Flutter dont working
I tried various methods, if the link is wrong, then it should at least be displayed json text in terminal
photo should be shown
Future<dynamic> getPhotoUrl(int profileID) async {
print("get Photo url $profileID");
var client = http.Client();
var url = Uri.parse("$profileBaseUrl/api/v2/profiles/$profileID/photos");
Map<String, String> headers = {
'APIVersion': '1',
"Authorization": token,
};
var response = await client.get(url, headers: headers);
if (200 == response.statusCode) {
return response.body;
} else {
}
print("avatar url: $currentPhotoUrl");
}
tried this and it doesn't work
Future<void> getPhotoUrl(int profileID) async {
print("get photo url $profileID");
var client = http.Client();
Map<String, String> headers = {
"Authorization": token
};
final http.Response response = await client.get(
Uri.parse("$profileBaseUrl/api/v2/profiles/$profileID/photos"),
headers: headers);
if (response.statusCode == 200) {
Map responseBody = jsonDecode(response.body);
var data = responseBody["data"];
if (data.length < 1) {}
else {
currentPhotoUrl.value = data[0]["content"][0]["medium"];
}
} else {
throw WebSocketException("server error: ${response.statusCode}");
}
print("photos url: $currentPhotoUrl");
}

Flutter Laravel Api returns no response

i have a getx controller where i created a register user function, but when i call it from the register ui nothing seems to happen
RxBool isLoading = false.obs;
final Uri uri = Uri.parse(url + 'register');
Future registerUser(name, email, password) async {
try {
// Register user
isLoading.value = true;
final http.Response response = await http.post(
uri,
headers: {
'Content-type': 'application/json',
'Accept': 'application/json',
},
body: jsonEncode({
'name': name,
'email': email,
'password': password,
}),
);
isLoading.value = false;
final res = json.decode(response.body);
if (res['success'] == true) {
print(res);
} else {
print(res);
}
} catch (e) {
print(e);
}
}

Flutter How to send Http (post) Request using WorkManager Plugin

Hello Guys any help will be apprecited please,
I am unable to send Http post or get request using workmanager plugin in flutter, any solutions to this would be highly appreciated, thanks
Here is my code
any help will be appreciated
thanks
Workmanager.executeTask((task, inputData) async {
switch (task) {
case fetchBackground:
print('checkStatusnow');
final sharedPref = await SharedPreferences.getInstance();
pendingStat = sharedPref.getBool('pendingStat');
print('pendingStat $pendingStat');
// await initialStat();
String url = 'https://getStat.com/chargeStat';
try {
var param = {
'authorization_code': authoStatCode,
'email': umail,
'amount': StatFare *100,
};
String body= json.encode(param);
var response = await http.Client().post(Uri.parse(url), headers: <String, String>{
'Authorization': StatKey,
'Content-Type': 'application/json',
'Accept': 'application/json'
},body: body,
);
if (response.statusCode == 200) {
print(response.body);
print("Successfull");
final data = jsonDecode(response.body);
print(data);
if (StatFounds == null) {
print("Status Not found");
}
else {
print ('checkForSta');
}
}
else {
print(response.reasonPhrase);
print("not available");
sharedPref.setBool("Stat", true);
}
} catch (e) {
}