I was working on a project that uses flutter for UI and HTTP requests that takes data from json file that i wrote and hosted by myself ( http://json-crud-file.epizy.com/file/file )
I used function below to fetch data :
Future fetchData() async {
final response =
await http.get(Uri.parse('http://json-crud-file.epizy.com/file/file'));
if (response.statusCode == 200) {
print(response.body);
} else {
print('faild fetching');
}
}
Then i get that error in console :
I/flutter (11924): <html><body><script>document.cookie="_test=4c9ff9225c7521d4102dc4ecb6f6be1e ; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/" ;document.location.href="http://json-crud-file.epizy.com/file/file?i=1";</script></body></html>
But when i use the same code but in diffrent json file in https://dummyjson.com/products i get json response code below:
Future fetchData() async {
final response =
await http.get(Uri.parse('https://dummyjson.com/products'));
if (response.statusCode == 200) {
print(response.body);
} else {
print('faild fetching');
}
}
response :
{"products":[{"id":1,"title":"iPhone 9","description":"An apple mobile which is nothing like apple","price":549,"discountPercentage":12.96,"rating":4.69,"stock":94,"brand":"Apple","category":"smartphones","thumbnail":"https://dummyjson.com/image/i/products/1/thumbnail.jpg","images":["https://dummyjson.com/image/i/products/1/1.jpg","https://dummyjson.com/image/i/products/1/2.jpg","https://dummyjson.com/image/i/products/1/3.jpg","https://dummyjson.com/image/i/products/1/4.jpg","https://dummyjson.com/image/i/products/1/thumbnail.jpg"]},{"id":2,"title":"iPhone X","description":"SIM-Free, Model A19211 6.5-inch Super Retina HD display with OLED technology A12 Bionic chip with ...","price":899,"discountPercentage":17.94,"rating":4.44,"stock":34,"brand":"Apple","category":"smartphones","thumbnail":"https://dummyjson.com/image/i/products/2/thumbnail.jpg","images":["https://dummyjson.com/image/i/products/2/1.jpg","https://dummyjson.com/image/i/products/2/2.jpg","https://dummyjson.com/image/i/products/2/3.jpg","https:/}
Related
i am new to flutter web but this error is crazy my func to get json data is
#override
Future<List<StoryEntity>> getNewAnimation(int id) async{
print("ali");
return (json.decode(
(await http.Client().get(Uri.parse('https://hekayatname.ir/home/getanimation')))
.body)['list'] as List)
.map(
(e) => StoryEntity(
title: e['fullname'],
imagePath: e['logo_url'],
description: "e['description']",
rating: 1,
galleryImagesPath: [],
id: e['id'],
producer: e['address'],
),
).toList();
}
but i recive nothing in flutter.
in web browser my data is like this just go to this link
https://hekayatname.ir/home/getanimation
i change the code to this
Future<List<StoryEntity>> getNewAnimation(int id) async{
print("1");
final response = await http.Client().get(Uri.parse("https://hekayatname.ir/home/getaudioestory"));
if(response.statusCode == 200){
print("2");
}
else{
print("3");
print(response.statusCode);
}
}
i have nothing to both if and else
if not work,else not work.... need help!!
Visit this link. Copy your json response and paste in the json section. Give your class name and hit Generate Dart.
Now hit copy dart code and add it your project. Then you can use it like inside the success case.
Note if you face any error of Null object. Thats mean your response contains null values and replace this data type with the corresponding data type.
if(response.statusCode == 200){
print('2');
YourJsonResponse obj = YourJsonResponse.fromJson(jsonDecode(response.body));
} else{
print("3");
print(response.statusCode);
}
Despite both urls showing the same json data, my code only works with the url "https://5f210aa9daa42f001666535e.mockapi.io/api/products" but the other. Wonder why and been struggling for 3 nights for this:
Future<List<Product>> fetchProducts() async {
const String apiUrl =
"http://10.0.2.2:8000/api/book";
//"https://5f210aa9daa42f001666535e.mockapi.io/api/products";
final response = await http.get(apiUrl);[enter image description here][1]
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
List<Product> products = (json.decode(response.body) as List)
.map((data) => Product.fromJson(data))
.toList();
// Return list of products
return products;
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load');
}
I think, you try this way. Using package: dio
https://pub.dev/packages/dio
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 :(');
}
}
My goal:
I want to make a get request to the RestApi that is running on the device in my local network to retrieve JSON data generated by the device.
What happens
The RestApi correctly responds to the browser call from every other device in the network. Bash's curl also works, however when I try to access the data through dart's http.get the program fails to retrieve the JSON data - I'm getting Statuscode 400.
Browser call result
What I have tried:
Messing with URL to make sure it's written correctly,
Setting up headers {"content" : "application/json"}
Using no (default) headers
Running the API call from separate dart file and from function embedded in flutter app. Both resulted in Statuscode 400, though flutter provided some more bug information:
Unhandled Exception: SocketException: OS Error: No route to host, errno = 113. I believe I have also seen the errno = 111 when I tried something else.
Using lower level HttpClient instead of Http
In the flutter app, I can connect to the data stored on firebase through http.get easily enough, but call to the device in local network results in the scenario described above.
Stand-alone dart file
import 'package:dart_http/dart_http.dart' as dart_http;
import 'package:http/http.dart' as http;
import 'dart:io';
import 'dart:convert';
main(List<String> arguments) async {
var url = 'http://192.168.0.5/api/device/state';
http.Response response1 =
await http.get(url, headers: {"content": "application/json"});
print('Response status: ${response1.statusCode}');
print('Response body: ${response1.body}');
print('Response body: ${response1.headers}');
print('Response body: ${response1.reasonPhrase}');
print('Response body: ${response1.request}');
HttpClient()
.getUrl(Uri.parse(
'http://192.168.0.5/api/device/state/')) // produces a request object
.then((request) => request.close()) // sends the request
.then((response) {
print(response);
response.transform(Utf8Decoder()).listen(print);
}); // transforms and prints the response
}
Call-embedded in flutter project
Future<Map<String, String>> getAirSensorStatus() async {
print("Getting Air Sensor");
http.Response response =
await http.get('http://192.168.0.5/api/device/state');
print(response);
print("Status code " + "${response.statusCode}");
try {
if (response.statusCode != 200 && response.statusCode != 201) {
print("Something went wrong. Status not 200 and not 201 for AirSensor");
return null;
}
final responseData = json.decode(response.body);
return responseData;
} catch (error) {
print(error);
return null;
}
}
I'm expecting to get statuscode 200 and JSON data in the response. Instead, only a response object is created and no connection established.
Could you help me figure out why is that?
The link to the documentation of the API I'm trying to access:
https://technical.blebox.eu/
The issue seems likely to be caused by the client unable to reach the local server on the request. HTTP error 400 is labelled as "Bad request" and "No route to host, errno = 113" usually caused by network error. A common fix to this issue is to ensure that the client is on the same network the local server is hosted in.
How do i read HttpRequest data sent by POST method from client, on the server, in Dart?
I send a message from the client like this:
HttpRequest request = new HttpRequest();
var url = "http://127.0.0.1:8081";
request.open("POST", url, async: false);
String data = 'hello from client';
request.send(data);
On server i am catching the request like this:
HttpServer.bind('127.0.0.1', 8081).then((server) {
server.listen((HttpRequest request) {
//DATA SHOULD BE READ HERE
});
});
But i cant figure out how to actually read the data... There is not data property in HttpRequest nor anything else...
EDIT This is how i get the answer now:
HttpServer.bind('127.0.0.1', 8081).then((server) {
server.listen((HttpRequest request) {
//DATA SHOULD BE READ HERE
print("got it");
print(request.method);
if(request.method == "POST") {
print("got it 2");
List<int> dataBody = new List<int>();
request.listen(dataBody.addAll, onDone: () {
var postData = new String.fromCharCodes(dataBody);
print(postData);
});
}
});
});
But for some reason the request.method is not "POST" but "OPTIONS", and if i change to if(request.method == "OPTIONS") , then print(postData) will still return nothing...
You can use the StringDecoder to tranform from "List of Int" to "String" from the HttpRequest. Since no matter if you send json, plain text, or png, Dart always send data in form of
"List of Int" to the server.Another means is to use the Streams (http://www.dartlang.org/articles/feet-wet-streams/) tested on Heroku Steam v0.6.2 Dart Editor 0.4.3_r20602 Dat SDK 0.4.3.5_r26062
For example,
the client:
import 'dart:html';
import 'dart:json' as Json;
import 'dart:async';
import 'dart:uri';
final String data = 'Hello World!';
void _sendPNG(String pngData) {
HttpRequest request = new HttpRequest(); // create a new XHR
// add an event handler that is called when the request finishes
request.onReadyStateChange.listen((_)
{
if (request.readyState == HttpRequest.DONE &&
(request.status == 200 || request.status == 0)) {
// data saved OK.
print(request.responseText); // output the response from the server
}
}
);
// POST the data to the server Async
print('Sending Photos to the server...');
var url = "/png";
request.open("POST", url);
request.setRequestHeader("Content-Type", "text/plain");
request.send(data);
}
the server:
import 'dart:io';
import 'dart:async';
import 'dart:json' as Json;
import "package:stream/stream.dart";
import 'package:xml/xml.dart' as xml;
import 'package:unittest/unittest.dart';
import 'package:rikulo_commons/mirrors.dart';
void receivePNG(HttpConnect connect){
var request = connect.request;
var response = connect.response;
if(request.uri.path == '/png' && request.method == 'POST')
{
String png='';
response.write('The server received png request!');
//read incoming List<int> data from request and use StringDecoder to transform incoming data to string
var stream = request.transform(new StringDecoder());
stream.listen((value){
print(value);
//Hello World!
}
else
{
response.write('error');
response.statusCode = HttpStatus.NOT_FOUND;
connect.close();
}
}
configure.dart
var _mapping = {
"/": home,
"/png": receivePNG,
};
Right now, the handling of POST data is a little difficult. But essentially the HttpRequest itself has to be 'listened' to. HttpRequest is a stream itself. In particular it's a Stream<List<int>>. So basically your data may be passed to your HttpRequest as multiple List<int>'s. So we need to reconstruct the data then convert it into a string (assuming you're expecting a string, not binary data, etc). Here's more or less what I do:
HttpServer.bind('127.0.0.1', 8081).then((server) {
server.listen((HttpRequest request) {
if(request.method == "POST") {
List<int> dataBody = new List<int>();
request.listen(dataBody.addAll, onDone: () {
var postData = new String.fromCharCodes(dataBody);
// Do something with the data now.
});
}
request.response.close();
});
Note that the request.listen(dataBody.AddAll, ...) basically calls List.addAll() each time data is to the server (in cases of larger data or multi-part forms it may not come all at once). This ensures we buffer it all until the stream indicates it is 'done' In which case we can now do something with the data we received, like convert it to a string.
I have found this useful example with client/side code
GitHub json send to server Example
// XXX: Dart Editor thinks this is OK, but I haven't run it.
import 'dart:html';
String encodeMap(Map data) {
return data.keys.map((k) {
return '${Uri.encodeComponent(k)}=${Uri.encodeComponent(data[k])}';
}).join('&');
}
loadEnd(HttpRequest request) {
if (request.status != 200) {
print('Uh oh, there was an error of ${request.status}');
return;
} else {
print('Data has been posted');
}
}
main() {
var dataUrl = '/registrations/create';
var data = {'dart': 'fun', 'editor': 'productive'};
var encodedData = encodeMap(data);
var httpRequest = new HttpRequest();
httpRequest.open('POST', dataUrl);
httpRequest.setRequestHeader('Content-type',
'application/x-www-form-urlencoded');
httpRequest.onLoadEnd.listen((e) => loadEnd(httpRequest));
httpRequest.send(encodedData);
}