How to reduce the api loading time flutter - api

I am using rest apis for displaying the data ,but for api loading it takes more time how can i reduce that time in flutter.
Future getData0() async {
Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
final SharedPreferences prefs = await _prefs;
var receivedToken = "Bearer " + prefs.getString("BearerToken");
var receivedstoreid=prefs.getString("store_id");
http.Response res = await http.get(
"http://Domainname.com/api/rest/cart",
headers: {
'Authorization': receivedToken,
'X-Oc-Store-Id': receivedstoreid,
},
);
Map mapRes = jsonDecode(res.body);
print('Response from server: $mapRes');
get_cart_item = GetCart.fromJson(mapRes);
print(get_cart_item.toJson());
I am calling the get and post apis like this way.

Related

Couldn't upload image to server in Flutter Web

I've created a flutter application for android and web. In Flutter web, I tried to upload image to server just like it works with firebase. But it is not working somehow. I've seen some solutions for this task. But I wonder, what is actually wrong with my code.
final url = Uri.parse('$apiHeader/poststore');
String token = await getUserToken();
Map<String, String> headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token'
};
var request = http.MultipartRequest("POST", url);
request.headers.addAll(headers);
request.fields['category_id'] = model.categoryId;
request.fields['title'] = model.title;
//I want to know about this section of the code, how can i make it work
if (kIsWeb) {
final fileBytes =
await model.image.readAsBytes(); // convert into bytes
var multipartFile = http.MultipartFile.fromBytes(
'fileName[]', fileBytes); // add bytes to multipart
request.files.add(multipartFile);
} else {
var multipartFile = await http.MultipartFile.fromPath(
'fileName[]', model.image.path);
request.files.add(multipartFile);
}
var response = await request.send();

xamarin.forms ,Foursqaure api response is not displaying but works in postman and foursqaure site after providing api key ?where im wrong

private async Task GetresultAsync()
{
var client = new HttpClient();
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri("https://api.foursquare.com/v3/places/search?ll=15.3494005,75.142583&query=shops&fields=geocodes,categories,name,hours,fsq_id,price,rating,stats,location"),
Headers =
{
{ "Accept", "application/json" },
{ "Authorization", "fsq322aNlTt3+PuRKw5js/ndngtry/XxNV0Q70yzKjDTQn0="
},
},
};
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
Debug.WriteLine(body);
}
Please any suggestions? I'm very new to xamarin and I'm getting data in postman but not getting result in xamarin using
RESTCLIENT OR HTTPCLIENT for( foursqaure places api for v3) where am I wrong?

Non Pro CoinBase API Invalid Signature

i've been trying to get some data from the non pro CB via their API.
I've been able to get data from coinbase pro, with the code below, adding the passphrase, but no dice with CB...
I keep getting invalid signature :(
Any idea what i could be missing?
const signedMessages = async (timestamp, meth, requestPath) => {
const secret = process.env.cb_all_read_secret;
const method = meth.toUpperCase();
const body = '';
const message = timestamp + method + requestPath + body;
const key = Buffer.from(secret, 'base64');
const hmac = crypto.createHmac('sha256', key);
const cb_access_sign = hmac.update(message).digest('base64');
return cb_access_sign;
};
const listAccounts = async () => {
let timestamp = Math.floor(Date.now() / 1000);
const signed = await signedMessages(timestamp, 'GET', '/v2/accounts');
const url = 'https://api.coinbase.com/v2/accounts';
const options = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'CB-ACCESS-KEY': process.env.cb_all_read_key,
'CB-ACCESS-SIGN': signed,
'CB-ACCESS-TIMESTAMP': timestamp,
},
};
console.log(options);
try {
const data = await fetch(url, options);
const resultat = await data.json();
console.log(resultat);
} catch (error) {
console.log('error: ', error.message);
}
};
listAccounts();
First thing I'd check is that your computer's clock is up to date i.e. not > 30 seconds behind the API server.
coinbase documentation is frustrating at best.
In one place I saw the method you're using being documented.
var what = timestamp + method + requestPath + body;
// decode the base64 secret
var key = Buffer(secret, 'base64');
// create a sha256 hmac with the secret
var hmac = crypto.createHmac('sha256', key);
// sign the require message with the hmac
// and finally base64 encode the result
return hmac.update(what).digest('base64');
When I went to find it again I found the following: documentation which does the signing a little differently:
var signature = crypto.createHmac("sha256", apiSecret).update(message).digest("hex");
Notice the lack of a base64 buffer and the digest is Hex.
I modified your code and was able to get the wallets with view permissions. I would probably create a sign function using the code in the link provided including the body for any options you need to include.
const signedMessages = async (timestamp, method, path) => {
const apiSecret = '...';
const bodyStr = '';
let message = timestamp + method.toUpperCase() + '/v2/' + path + bodyStr;
return crypto.createHmac('sha256', apiSecret).update(message).digest('hex');
};
const listAccounts = async () => {
let timestamp = Math.floor(Date.now() / 1000);
const signed = await signedMessages(timestamp, 'GET', 'accounts');
const url = 'https://api.coinbase.com/v2/accounts/';
const options = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'CB-ACCESS-KEY': '...',
'CB-ACCESS-SIGN': signed,
'CB-ACCESS-TIMESTAMP': timestamp,
},
};
console.log(options);
try {
const data = await fetch(url, options);
const resultat = await data.json();
console.log(resultat);
} catch (error) {
console.log('error: ', error.message);
}
};
listAccounts();
but guess what...
the "deprecated" node api does it the same way (that's where I found this signing method before I found the documentation) and it was last updated 4 years ago. Go figure.

I can fetch data but when im not using the app after 1-2days, fetching data not working anymore. (Flutter)

//Am i doing wrong way?
Im fetching the data at first but after 1-2days of not using the app, fetching data is not working anymore.
Future<List<TopCourses>> fetchTopCourseList() async {
final prefs = await SharedPreferences.getInstance();
final accessToken = prefs.getString('access_token');
final response = await client.get(
URL_STUDENT_GET_TOP_COURSES,
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": "Bearer " + accessToken,
},
);
if (response.statusCode < 200 || response.statusCode > 400) {
throw Exception('Failed to Load');
} else {
return compute(topcourseFromJson, response.body);
}
}
List<TopCourses> topcourseFromJson(String str) {
final jsonData = json.decode(str);
return new List<TopCourses>.from(
jsonData["top"].map((x) => TopCourses.fromJson(x)));
}
Either your accessToken has expired, or the accessToken you're trying to get from SharedPreferences has been wiped from your app data.
trying checking that your access token is not null
and the token has not to expired

Find out Cookie in Flutter

I use Flutter to make a HTTP-Post to a website to login. If I only send the data to login, the response of the HTTP-Post shows, that I`m not logged in. I tried to find out the cookie the Website sends. I did it with the software Postman. If I add the same cookie, I got at Postman, the HTTP-Post with Flutter works and the response shows, that Im logged in. After a while, the value of the cookie switched and the HTTP-Post via Flutter doent work.
How can I get the information about the actual value of the cookie from the website?
The code looks like this:
Future initiate() async {
ByteData bytes = await rootBundle.load('assets/Certificates/test.crt');
SecurityContext clientContext = new SecurityContext()
..setTrustedCertificatesBytes(bytes.buffer.asUint8List());
var client = new HttpClient(context: clientContext);
IOClient ioClient = new IOClient(client);
var form = <String, String>{
'user':'testuser',
'pass':'testpass',
'logintype':'login',
'pid':'128',
'submit':'Anmelden',
'tx_felogin_pi1[noredirect]':'0'
};
print(form);
var ris = await ioClient.get("https://www.test.de/login");
print(ris.headers);
http.Response res = await ioClient.post("https://www.test.de/login",body:form, headers: {
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded", "Cookie": "fe_typo_user=12345"}, encoding: Encoding.getByName("utf-8"));
ioClient.close();
client.close();
print(res.body.length);
return res.body.contains("logout");
}
This is how I get cookie:
static Future<String> login(String username, String password) async {
var url = _session._getUrl('/auth/login');
var map = new Map<String, dynamic>();
map['username'] = username;
map['password'] = password;
final response = await http.post(url, body: map);
var jsonResponse = convert.jsonDecode(response.body);
var cookies = response.headers['set-cookie'];
if (cookies != null) {
var csrf = _session._getCSRF(cookies);
LocalStorage.instance.setString('CSRF', csrf);
print(csrf);
}
return jsonResponse['msg'];
}