Send list to server without json_encode dart - flutter

Iam using http package to communicate with the server.
How to send an list to php file in the server without json_encode in Dart with Flutter.
dynamic result = null;
List ids = [12, 65, 7];
Map data = {
'name': 'Mark',
'ids': ids,
};
var client = new http.Client();
await client.post('https://example.com/control/',
headers: {
"Accept": "application/json",
},
body: data,)
.then((response) => result = jsonDecode(response.body));
My code above dont work, The problem is I need to write json_encode(ids) to send the data, and when I want to get the array/list in my php file I need to write json_decode($this->input->post('ids'))
How to solve it without json_encode and json_encode, how to send an json object which can accept arrays without any problem?

I don't understand completely what is the problem with sending json but you may convert your list to string like:
final idsSerialized = ids.map((id) => '$id').join(',');
Then send this string as payload of POST request to php script which can read value via _POST array (or your favorite way) and restore this serialized string to array:
$ids = explode($_POST['ids'], ',');

Related

How to retrieve/decode json/map from downloaded ByteStream?

I have a ByteStream downloaded from a Server, namely datas regarding the user.
Its in MySql server as
"username":"Neor","totalCoins":"350"
The truncated part of .php file that gives-away this data, is as follows:
$data = $stmt->fetchColumn();
header($_SERVER["SERVER_PROTOCOL"] . " 200 OK");
header("Cache-Control: public");
header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: Binary");
header("Content-Length:".strlen($data));
echo $data;
I use ths Flutter code to download the data:
Future<void> downloadData() async {
var url = Uri.parse("https://example.com/mycloud.php");
var request = http.MultipartRequest('POST', url)
..fields["user"] = "Dia";
var response = await request.send();
var stream = response.stream; }
On checking if the downloaded ByteStream contains anything, I've used print(stream.length), which prints out as 137.
How can I get the information I want from the ByteStream?
(If my question lacks in any way, please let me know.)
There shouldn't be any need to use a multipart request for a simple POST. Instead use the simpler http.post method.
Future<void> downloadData() async {
final response = await http.post(
Uri.parse('https://example.com/mycloud.php'),
body: <String, String>{
'user': 'Dia',
},
);
final decodedJson = json.decode(response.body);
// if you want to ensure the character set used, replace this with:
// json.decode(utf8.decode(response.bodyBytes));
}
If you do stick with the stream way, you have a Stream<List<int>> that you want to turn initially into a List<int>. Use the toList() method on stream for that. Then you have to decode that into characters. JSON is always encoded in utf8, so you could:
json.decode(utf8.decode(await stream.toList()));
(Under the hood, http is basically doing that for you; collecting the stream together and doing the character decoding and presenting that as body.)
First
import 'dart:convert' show utf8;
String foo = utf8.decode(bytes);
Then
Map valueMap = json.decode(foo );

Flutter form with attachment (file upload)

I am trying to build a Flutter form with 2 text fields and 1 field for an attachment:
Text Field 1
Text Field 2
Attachment
Send Data Button
This is to make a POST request and send these 3 values to my server, store the file locally and get the name of the file in the database. This backend logic is already covered.
I was trying to use a MultiPart request as follows:
Future makePostRequest(
String title, int subjectid, int teacherid, String limitDate) async {
var url = Uri.parse('http://localhost:8000/newHomework');
var request = http.MultipartRequest('POST', url);
var headers = {'Content-Type': 'text/plain; charset=UTF-8'};
print(this.file);
Uint8List data = await file.readAsBytes();
List<int> list = data.cast();
request.files
.add(http.MultipartFile.fromBytes('text', list, filename: 'tarea1'));
request.headers.addAll(headers);
request.fields['title'] = title;
request.fields['limitDate'] = limitDate;
request.fields['subjectid'] = subjectid.toString();
request.fields['teacherid'] = teacherid.toString();
request.fields['ext'] = '.txt';
var res = await request.send();
return res.stream.bytesToString().asStream().listen((event) {
var parsedJson = json.decode(event);
print(parsedJson);
});
}
But I do not know how to do this:
Include a button in the form to add the attachment (will only be text files, and only 1 file always) and then send all of this information with the Send Data Button.
Maybe I am approaching this from an incorrect perspective... Any ideas on how to do this?
Update makePostRequest method, now getting error: Error: NoSuchMethodError: 'readAsBytes'

Converting my Postman Call to Dart/Flutter API Call

I hope to use nutritionix api to get food information for the users of my application, I manage to get the call to work in Postman, however I cannot convert it to dart code. I am getting this error: '{message: Unexpected token " in JSON at position 0}'
Here is my (POST) postman call:
Here is my attempt at converting that to dart code:
Future<void> fetchNutritionix() async {
String url = 'https://trackapi.nutritionix.com/v2/natural/nutrients';
Map<String, String> headers = {
"Content-Type": "application/json",
"x-app-id": "5bf----",
"x-app-key": "c3c528f3a0c68-------------",
"x-remote-user-id": "0",
};
String query = 'query: chicken noodle soup';
http.Response response =
await http.post(url, headers: headers, body: query);
int statusCode = response.statusCode;
print('This is the statuscode: $statusCode');
final responseJson = json.decode(response.body);
print(responseJson);
//print('This is the API response: $responseJson');
}
Any help would be appreciated! And, again thank you!
Your postman screenshot shows x-www-form-urlencoded as the content-type, so why are you changing that to application/json in your headers? Remove the content type header (the package will add it for you) and simply pass a map to the body parameter:
var response = await http.post(
url,
headers: headers,
body: {
'query': 'chicken soup',
'brand': 'acme',
},
);
Also you can now generate Dart code (and many other languages) for your Postman request by clicking the Code button just below the Save button.
click the three dotes button in request tab and select code option then select your language that you want convert code to
review the query you're posting
your Postman input is x-www-form-urlencoded instead of plain text
String query = 'query: chicken noodle soup';
why don't you try JSON better
String query = '{ "query" : "chicken noodle soup" }';

http.post is being fired twice

I am a bit new to Flutter, and I am building a screen that posts data to an API built in PHP mon my hosting server. The API is built by me which receives a JSON object and then saves the data.
The app is working fine, and API is receiving the data, but the http.post seems is firing twice ( calling the API twice)
Which makes my API saves the record twice. there is no possible way for me to check before adding the send record. as My API simply saves a new record so whenever it receives a call it simply saves it and returns back a value for the mobile App ( built in Flutter).
If I use a condition to check, this way the first call will return correct data to the mobile app, but the second one will return an error for the mobile app since the record already exists.
I have read about the Access-Control-Allow-Origin and how it might be the issue and put it my my .httaccess file
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
but no luck.
any idea.
Note I am using a shared hosting.
Code I use in Flutter:
class _PostADToServerState extends State<PostADToServer> {
Future<List<JSBResponse>> _postRequest() async {
// print('Call API function is called');
Map<String, dynamic> myAd = {
"isbn10": widget.title.isbn10,
"isbn13": widget.title.isbn13,
... [Some fields]
"titleCondition": widget.title.titleCondition,
"priceIs": widget.title.priceIs,
"school_name": widget.title.schoolName
};
String json = jsonEncode(myAd);
var url = 'https://www.example.com/xapis/save_new_ad.php';
var body = json;
var data = await http.post(url,
headers: {
"Content-Type": "application/json",
"accept": "application/json",
"Access-Control-Allow-Origin": "*",
},
body: body);
var jsonData = jsonDecode(data.body);
Code in my PHP API starts with the following:
$data = file_get_contents('php://input');
$theTitle = json_decode($data);
Then I use the content I find in the $theTitle object as the following:
$title = $theTitle->title;

Flutter http Maintain PHP session

I'm new to flutter. Basically I'm using code Igniter framework for my web application. I created REST API for my web app, after user login using API all the methods check for the session_id if it exists then it proceeds, and if it doesn't then it gives
{ ['status'] = false, ['message'] = 'unauthorized access' }
I'm creating app with flutter, when i use the http method of flutter it changes session on each request. I mean, it doesn't maintain the session. I think it destroys and creates new connection each time. Here is thr class method which i use for api calls get and post request.
class ApiCall {
static Map data;
static List keys;
static Future<Map> getData(url) async {
http.Response response = await http.get(url);
Map body = JSON.decode(response.body);
data = body;
return body;
}
static Future postData(url, data) async {
Map result;
http.Response response = await http.post(url, body: data).then((response) {
result = JSON.decode(response.body);
}).catchError((error) => print(error.toString()));
data = result;
keys = result.keys.toList();
return result;
}
I want to make API request and then store session_id,
And is it possible to maintain session on the server so i can manage authentication on the web app it self.?
HTTP is a stateless protocol, so servers need some way to identify clients on the second, third and subsequent requests they make to the server. In your case you might authenticate using the first request, so you want the server to remember you on subsequent requests, so that it knows you are already authenticated. A common way to do this is with cookies.
Igniter sends a cookie with the session id. You need to gather this from each response and send it back in the next request. (Servers sometimes change the session id (to reduce things like clickjacking that we don't need to consider yet), so you need to keep extracting the cookie from every response.)
The cookie arrives as an HTTP response header called set-cookie (there may be more than one, though hopefully not for simplicity). To send the cookie back you add a HTTP request header to your subsequent requests called cookie, copying across some of the information you extracted from the set-cookie header.
Hopefully, Igniter only sends one set-cookie header, but for debugging purposes you may find it useful to print them all by using response.headers.forEach((a, b) => print('$a: $b'));. You should find Set-Cookie: somename=abcdef; optional stuff. We need to extract the string up to, but excluding the ;, i.e. somename=abcdef
On the next, and subsequent requests, add a request header to your next request of {'Cookie': 'somename=abcdef'}, by changing your post command to:
http.post(url, body: data, headers:{'Cookie': cookie})
Incidentally, I think you have a mismatch of awaits and thens in your code above. Generally, you don't want statics in classes, if they should be top level functions instead. Instead you could create a cookie aware class like:
class Session {
Map<String, String> headers = {};
Future<Map> get(String url) async {
http.Response response = await http.get(url, headers: headers);
updateCookie(response);
return json.decode(response.body);
}
Future<Map> post(String url, dynamic data) async {
http.Response response = await http.post(url, body: data, headers: headers);
updateCookie(response);
return json.decode(response.body);
}
void updateCookie(http.Response response) {
String rawCookie = response.headers['set-cookie'];
if (rawCookie != null) {
int index = rawCookie.indexOf(';');
headers['cookie'] =
(index == -1) ? rawCookie : rawCookie.substring(0, index);
}
}
}