Flutter First Http Request Not Firing - http

I'm developing a Flutter application, now working on authentication. When a user enters their credentials, I send a post request to my server (.NET Core). The problem is the first request (login in this case) doesn't fire and doesn't timeout, basically it stays in an infinite loop. If I change something in the app that triggers a hot reload, then the request fires and the next ones work just fine. Seems like a odd behaviour.
I've tried to await for the response and also tried using .then() clause, both have the same behaviour:
Future<Response> post(String path, String body) async {
final response = await http.post(url + path, headers: {
HttpHeaders.contentTypeHeader: 'application/json'
}, body: body);
// .then((res) => print(res));
...
}
Been stuck on this for 2 days and can't find a logical explanation for this behaviour. Anyone has/had the same problem?

I hope this should help you
post(String path, String body) async {
final response =
await http.post(url + path,
headers: { HttpHeaders.contentTypeHeader: 'application/json' },
body: body);
print (response.body());
}

Related

Deno - How to fetch data from distant API or URL?

I'm wondering how I can get data from other servers and API with deno ? Everything in the documentation teach me about making http servers and read files from local source. But I can't find anything useful about reading something on the network.
How can read JSON data from the Stripe API ? Or if I want to read a HTML file with text inside ?
Thank you for your time!
I am just giving you an example of the GET request for fetching repositories of Github.
You can change the URL and Request Configuration as per your need.
In the code given below, I am calling another API of Github. By using the fetch() method you can do that.
fetch() method first takes the URL as the first parameter and the next parameter is RequestInit which takes the request method type, headers, body, etc and at the end returning JSON response of that API call.
const githubResponse = async (): Promise<any> => {
const response = await fetch("https://api.github.com/search/repositories?q=android", {
method: "GET",
headers: {
"Content-Type": "application/json",
},
});
return response.json(); // For JSON Response
// return response.text(); // For HTML or Text Response
}
console.log(await githubResponse());
I have written the above code in a ts file named Testing.ts . So, you can run the above code by the command given below:
deno run --allow-net Testing.ts
Next, I am giving you a sample POST request code:
const githubResponse = async (): Promise<any> => {
const body: URLSearchParams = new URLSearchParams({
q: "AvijitKarmakar",
});
const response = await fetch("https://api.github.com/search/repositories", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: body
});
return response.json();
// return response.text(); // For HTML or Text Response
}
console.log(await githubResponse());
You can see that I have created a body object and passed it in the RequestInit through the body parameter and also changed the request method type to POST.
You'll need to do a HTTP Request, for that in Deno you use fetch, the same Web API the browsers use.
To read JSON response:
const res = await fetch('https://api.stripe.com');
const data = await res.json();
If you want HTML:
const res = await fetch('https://example.com');
const html = await res.text();
// Now you can use some HTML parsing lib
fetch requires the --allow-net flag.
Deno strives to be as close to the existent browser API as possible.
That means, you can use fetch. Example:
// fetch-kitten.ts
fetch("https://placekitten.com/200/300").then(async (d) =>
Deno.writeFile("kitten.jpg", new Uint8Array(await d.arrayBuffer()))
);
CLI:
deno run --allow-net --allow-write fetch-kitten.ts
Reference

The HTTP request is not being executed in response - Flutter/Dart

I'm trying to perform a request to a Web API written in C# (.NET Core). The endpoint runs a async function and return a JSON with result of operation.
In Dart I can't get the response. then() or catchError() just don't executes.
The endpoint get products in payload. When I send only one product I can get the response but when ai send two or more I can't.
The payload is:
http .post('http://192.168.0.10:5000/api/v1/oficina/dart',
body: jsonEncode({
"usuario": "edigleyssonsilva",
"senha": "123456",
"codEmp": 1,
"codFil": 1,
"produtos": [
{
"ccuRes": "160",
"codEmp": 1,
"codFil": 1,
"codPro": "570.0001",
"codTns": "90250",
"datPrv": "2020-02-17",
"datEme": "2020-02-17",
"qtdEme": 2
}
]
}),
headers: {'Content-Type': 'application/json'})
.then((value) => print(value.body))
.catchError((err) {
print('Ocorreu um erro');
print(err);
});
I already tested the same endpoint with the same payload on Postman, Angular app and on a test file written in Dart and this works perfectly.
So, I have no idea why it doesn't work in Flutter
It's not very clear tell with the code you shared, either also share the code calling this function, but you can also try, with assigning your body to a Map object, and then encode it with json.encode, as jsonEncode was deprecated in new versions, though it works, but you should use the new way to encode it.
Also, you should use async-await while doing any asynchronous work.
Future<void> request() async {
Map<String, String> headers = {
'Content-type': 'application/json',
'Accept': 'application/json',
};
Map body = {"usuario": "edigleyssonsilva",
"senha": "123456",
"codEmp": 1,
"codFil": 1,
"produtos": [
{
"ccuRes": "160",
"codEmp": 1,
"codFil": 1,
"codPro": "570.0001",
"codTns": "90250",
"datPrv": "2020-02-17",
"datEme": "2020-02-17",
"qtdEme": 2
}
]};
final response = await http.post(url,
body: json.encode(body),
headers: headers,
).catchError((err) {
print('Ocorreu um erro');
print(err);
});
print('Response: ${response.body}');
}
If this only happens when calling a service on localhost:
Change your url from http://localhost:8080/bla to
http://10.0.2.2:8080/bla.
The problem is that your emulator doesn't understand localhost, like your machine's localhost, so to access it you need to switch to 10.0.2.2

Loading image from http request

I'm developing a profile card that has to get different value's. I'm getting all the value's but i also want to load a network image. I'm using a filemaker server and i had noticed that i needed coockies to load this. When i make a request copy paste the image url into my browser it just loads. But whenever i'm loading it into my application i get the 401 statusCode with my image.
I have tried just a valid network image that's working, i have readed something about coockies but i'm not sure if i need to use them and how. I also find it weird that whenever i load the image in my browser it works but not on my application.
Future makeRequest() async {
var url4 =
"https://fms.xxxxxx.nl/fmi/data/v1/databases/Roscom Management Systeem/layouts/medewerker pa api/_find";
var body = json.encode({
"query": [
{"Emailadres(1)": "xxxx#xxx.nl"}
],
});
Map<String, String> headers = {
'Content-type': 'application/json',
'Accept': 'application/json',
"Authorization":
'Bearer xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
};
var response = await http.post(url4, body: body, headers: headers);
setState(() {
var responseJson = json.decode(response.body);
data = responseJson['response']['data'][0];
profielfoto = data['fieldData']['iMedewerker Foto'];
print(profielfoto);
});
Value i get in the terminal
I expect that i can load the image in a networkimage with just the var $profielfoto. I don't know what to do with the coockies or maybe there's a much easier way to do it. I hope someone can help me please let me know if i need to provide more information about the server or anything else. ;)
A few things. Please do not put any type of heavy processing in setState
https://docs.flutter.io/flutter/widgets/State/setState.html
Generally it is recommended that the setState method only be used to
wrap the actual changes to the state, not any computation that might
be associated with the change. For example, here a value used by the
build function is incremented, and then the change is written to disk,
but only the increment is wrapped in the setState:
setState tells the widget when it needs to be redrawn
https://flutter.dev/docs/cookbook/images/network-image
String _profilePhoto = "";
//Change await into an async operation
http.post(url4, body: body, headers: headers).then( (response) {
var responseJson = json.decode(response.body);
print(data['fieldData']['iMedewerker Foto']);
setState(() {
_data = responseJson['response']['data'][0];
_profilePhoto = data['fieldData']['iMedewerker Foto'];
});
})
Widget build(BuildContext context){
//Check if string is empty
if ( _profilePhoto == "" ){
return CircularProgressIndicator();
}else {
return Image.network( _profilePhoto );
}
}
https://flutter.dev/docs/cookbook/images/network-image
https://pub.dartlang.org/packages/cached_network_image
You have two choices to grab images from the network. I believe I presented one way.
the authorization token must be the issue. a secure server will return this token when a user logs in. then all ensuing request must have this token in the 'authorization header'. if it is not there or incorrect the server returns a 401

Chaining RxJS Observables with interval

my first question to the community out here!
i'm working on an app which does communicates to the API in the following way
step1: create request options, add request payload --> Post request to API
API responds with a request ID
Step2: update request options, send request ID as payload --> post request to API
final response: response.json
Now the final response can take a bit of time, depending on the data requested.
this can take from anywhere between 4 to 20 seconds on an average.
How do i chain these requests using observables, i've tried using switchmap and failed (as below) but not sure how do i add a interval?
Is polling every 4 second and unsubscribing on response a viable solution? how's this done in the above context?
Edit1:
End goal: i'm new to angular and learning observables, and i'm looking to understand what is the best way forward.. does chaining observable help in this context ? i.e after the initial response have some sort of interval and use flatMap
OR use polling with interval to check if report is ready.
Here's what i have so far
export class reportDataService {
constructor(private _http: Http) { }
headers: Headers;
requestoptions: RequestOptions;
payload: any;
currentMethod: string;
theCommonBits() {
//create the post request options
// headers, username, endpoint
this.requestoptions = new RequestOptions({
method: RequestMethod.Post,
url: url,
headers: newheaders,
body: JSON.stringify(this.payload)
})
return this.requestoptions;
}
// report data service
reportService(payload: any, method: string): Observable<any> {
this.payload = payload;
this.currentMethod = method;
this.theCommonBits();
// fetch data
return this._http.request(new Request(this.requestoptions))
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body || {};
}
private handleError(error: any) {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
in my component
fetchData() {
this._reportService.reportService(this.payload, this.Method)
.switchMap(reportid => {
return this._reportService.reportService(reportid, this.newMethod)
}).subscribe(
data => {
this.finalData = data;
console.info('observable', this.finalData)
},
error => {
//console.error("Error fetcing data!");
return Observable.throw(error);
}
);
}
What about using Promise in your service instead of Observable, and the .then() method in the component. You can link as much .then() as you want to link actions between them.

How to read received headers in Angular 2?

Can some body tell me how to read received headers in Angular 2?
i have mad a request, for login and password, and there should be sent back headers with Token. I need the token for further workaround.
here is part of the code:
sendLogin(username, password) {
let body = JSON.stringify({"username": username, "password": password});
let headers = new Headers({'Content-Type': 'application/json'});
let options = new RequestOptions({headers: headers});
return this.http.post(this.loginUrl, body, options)
.map(res => res.json())
.map((res) => {
if (res.ok) {
// at least how to console.log received headers?
console.log( res.headers); //undefined
this.loggedIn = res.ok;
} return res.ok;
});
};
thank you.
Most of the time such an issue is related to CORS. You need to explicitly enable allowed headers in the response headers.
You're only be able to see the header in the map only if it's enabled by CORS.
Your server needs to return the following in headers:
Access-Control-Allow-Headers: X-SomeHeader

Resources