Flutter Session - Get resaults by user session - mysql

I have flutter app where user input data and that data is stored on mysql.
Everything works perfect on my PHP, HTML on web. But in flutter I can't get session of user.
Future getData() async {
var url = 'https://azer.maverus.ba/api/read.php';
var response = await http.get(Uri.parse(url));
return json.decode(response.body);
}
I have that script and it read only data that I type inside flutter. And can't read data from database from curent user.

You have to add header to pass Authorization key to the API check the code below
Future getData() async {
var url = 'https://azer.maverus.ba/api/read.php';
var response = await http.get(Uri.parse(url),headers: <String, String>{
"Authorization" : "YOUR KEY HERE"
});
return json.decode(response.body);
}

Related

Flutter run -d chrome not fetch json url

I've create Board List function by fetching json url via flutter
First I've crated into window exe it works properly like this below
But when I want to production via chrome or android
It is not working as this below
This is my code to fetch json url what did I do wrong?
Future<List<Schedule>> fetchBoardList() async {
final response = await http.get('http://192.168.10.109:8888/mcschedule/machine/');
String logResponse = response.statusCode.toString();
if (response.statusCode == 200){
//print('ResponseStatusCode: $logResponse'); // Check Status Code = 200
//print('ResponseBody: ' + response.body); // Read Data in Array
List<dynamic> responseJson = json.decode(response.body);
return responseJson.map((e) => new Schedule.fromJson(e)).toList();
} else {
throw Exception('error :(');
}
}

Flutter json data from http.get is returning old database values in App and Latest values in Browser

final String url = "https://stsrefiners.com/wp-content/plugins/calculator/templates/mobilefixedval.php";
List data;
void initState()
{
super.initState();
//this.getJsonData();
Timer.periodic(Duration(seconds: 10), (timer) {
this.getJsonData();
});
}
Future<String> getJsonData() async
{
var response = await http.get(
Uri.encodeFull(url),
headers: {"Accept":"application/json"}
);
setState(() {
var convertDataToJson = json.decode(response.body);
data = convertDataToJson;
print(data);
_isLoading = true;
});
return "Success";
}
Data is fetched using the getJsonData Fucntion and in URL the data is fetched using the MYSQL database using mysqli method when I open the URL in browser it returns the latest values but when I fetch the data in application both in android and IOS it returns the old.
The data is not updating at run time
I'm also facing the same issue due to the Network cache setting in the browser.
Workaround solution
I added random URL query value in API call..
For Example:
my actual API URL
www.xyz.com?id=1
I changed this into
www.xyz.com?id=1&r=somerandomnumber (every call)

Get json Data from Rapid API in Flutter (Dart)

I managed to load the data from a Json File which is local on my Flutter Project. I also was able to fetch Data from the Internet, if the API Url was like:
https://[API-Server][parameter1:xy][parameter2:abc][API-KEY:lasgoewrijeowfjsdfdfiia]
I archieved that with this code sample:
Future<String> _loadStringFixtures() async {
return await rootBundle.loadString('assets/fixtures.json');
}
Future loadFixtures() async {
String jsonString = await _loadStringFixtures();
final jsonResponse = json.decode(jsonString);
FixturesAPI value = new FixturesAPI.fromJson(jsonResponse);
return value;
}
So far so good...
But now I am facing a problem with the API Provider RapidAPI
You can find the documentation etc. here:
https://rapidapi.com/api-sports/api/api-football/endpoints
As you can see they give some code snippets to connect to their API.
There are some for C, C#, Java, Python etc. You can look into all of them with the link above.
Sadly there is no example for Flutter.
And I do not see a way to adapt these examples.
Normally you can paste your API Key directly into the URL, but this seems not possible here? Or maybe it is?
Does Flutter also have other possibilities to receive data from an API besides the one I did?
Thank you so much in advance for your help!
It's possible to with http package and very easy. You can see in this example below...
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
class APIService {
// API key
static const _api_key = <YOU-API-KEY-HERE>;
// Base API url
static const String _baseUrl = "api-football-beta.p.rapidapi.com";
// Base headers for Response url
static const Map<String, String> _headers = {
"content-type": "application/json",
"x-rapidapi-host": "api-football-beta.p.rapidapi.com",
"x-rapidapi-key": _api_key,
};
// Base API request to get response
Future<dynamic> get({
#required String endpoint,
#required Map<String, String> query,
}) async {
Uri uri = Uri.https(_baseUrl, endpoint, query);
final response = await http.get(uri, headers: _headers);
if (response.statusCode == 200) {
// If server returns an OK response, parse the JSON.
return json.decode(response.body);
} else {
// If that response was not OK, throw an error.
throw Exception('Failed to load json data');
}
}
}
Then get you request:
//....
APIService apiService = APIService();
// You future
Future future;
//in the initState() or use it how you want...
future = apiService.get(endpoint:'/fixtures', query:{"live": "all"});
//....
Yes it possible in flutter. Use the Dio Package in flutter which is a powerful Http client. Using dio you can set interceptors to add api key to url so you don't have to append it in every request. Setting interceptors will help you.

how to store json response locally (sqflite database) in flutter

I did not able to store json response from API in sqflite database but i already parsed json response in list and also i stored similar data in sqflite database.
To stored locally i got success and able to perform CRUD operation and sending it to server, similarly i also able to perform CRUD operation on API data but problem arises on synchronization between local and json data.
the below code id for calling json data
Future<List<Activities>> getData() async {
List<Activities> list;
var res = await http
.post("http://xxxx/get-activity", headers: {
HttpHeaders.authorizationHeader: "Bearer " + _token.toString()
});
if (res.statusCode == 200) {
var data = json.decode(res.body);
var rest = data["data"] as List;
// print(rest);
list = rest.map<Activities>((json) => Activities.fromJson(json)).toList();
// print('okay, ${rest[0]}!');
} else {
print('something error');
}
print("List Size: ${list.length}");
return list;
}
solved
var data = json.decode(res.body);
var activities= data["data"] as List;
for (var activity in activities) {
Activity actData = Activity.fromMap(activity);
batch.insert(actTable, actData.toMap());
}
Solution! Please use this flutter plugin json_store

Http get request giving forbidden response in windows phone 8

HTTP "POST" data with login credentials to the BASEn server using API URL, in response it is giving a status 200, OK.
var values = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("mode", "login"),
new KeyValuePair<string, string>("user", logintxtbx.Text),
new KeyValuePair<string, string>("password", passtxtbx.Text)
};
httpClient = new HttpClient(new HttpClientHandler());
HttpResponseMessage response = await httpClient.PostAsync("https://xx-yyy.com/auth", new FormUrlEncodedContent(values)); var strin = response.StatusCode.ToString();
var responseString = await response.Content.ReadAsStringAsync();
MessageBox.Show("login Success");
GetFullResponse(httpClient);
}
After validating my credentials, the server will create a session to me if i try to do "GET" HTTP by using another urls, it should gives my required data but this thing was not happening, every time iam getting "403" forbidden response.
This is the code using for "GET" data.
var uri = new Uri("https://xx-yyy.com/_ua/web/web/v1/xyz/?xyx=1431369000000&end=1431436740000&_=1431436741550");
var Response = await httpClient.GetAsync(uri);
var statusCode = Response.StatusCode;
Response.EnsureSuccessStatusCode()
var ResponseText = await Response.Content.ReadAsStringAsync();
i don't know whats wrong, i was doing.
Can any one suggest me how can i do this to be happen.
var handler = new HttpClientHandler();
var cookieContainer = handler.CookieContainer;
var client = new HttpClient(handler);
store cookies using cookieContainer and use them to authenticate the future calls using the same way as on web.
Store the cookies to the phone using IsolatedStorageSettings
Reference for more details here