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
Related
It seems like has been asked a 1000 times but in reading all of the responses I still cannot seem to figure out how to make this work.
Here is my use case.
Make a call to an Auth Endpoint and return an access token
do some updates to the options of a 2nd API call
make the next api call with the updated options
I know how to make this work with traditional promises or callbacks but in my case step 1 & 2 could be optional so what I want to do is if step 1 & 2 are required call an async function to get the token and update the options. If 1 & 2 are not required then just make the 2nd API call.
I am trying to use axios but no matter what I do the response is either undefined or
Here is my code, can someone please explain the best way to do this, or is it just easier to use traditional promise\callbacks?
var options = {
'method': httpVerb ,
'url': url,
'headers': {
'Content-Type': 'application/json'
},
body: JSON.stringify(bodyArgs)
};
if(authBody){
auth = getAuth(authBody)
options.headers["Authorization"] = "Bearer " + auth.access_token;
console.log(auth)
}
const getAuth = async (options) => {
try{
const resp = await axios.post(options.authURL, options )
if(resp.status === 200){
return resp.data;
}else{
return ""
}
}catch(err){
console.error(err);
}
}
auth = getAuth(authBody) // wrong
getAuth is an async function, and async functions always return Promises even if the return statements within them return simple values.
If you want to wait for the return value of getAuth, you're going to have to do so in a then function on the return value, or await the result from within a different async function. Consequently, if you have an optional asynchronous step, it is safer to make the whole process appear asynchronous to abstract away the cases where you need to wait to refresh the token.
I'm trying to make a demo app with flutter and trying to fetch products from a demo magento site.
This is my code:
Future<List<Product>> fetchProducts() async {
final params = <String, String>{
'searchCriteria[filter_groups][0][filters][0][condition_type]': 'in',
'searchCriteria[filter_groups][0][filters][0][field]': 'type_id',
'searchCriteria[pageSize]': '20',
'searchCriteria[filter_groups][0][filters][0][value]': 'simple,configurable,bundle',
'searchCriteria[currentPage]': '1',
'searchCriteria[sortOrders][0][field]': 'created_at',
'searchCriteria[sortOrders][0][direction]': 'DESC'
};
var uri = Uri.parse('https://demo.com/rest/v1/default/products');
uri = uri.replace(queryParameters: params);
print(uri);
final response =
await http.get(uri, headers: {HttpHeaders.authorizationHeader: "Bearer qb7157owxy8a29ewgogroa6puwoafxxx"});
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON.
final data = json.decode(response.body);
final products = data["items"] as List;
return products.map<Product>((json) => Product.fromJson(json)).toList();
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
When I debugged, the response was 400 - Bad request. I guess that because the uri was encoded to include percentage characters as I printed as below:
So how can I disable encoding the uri?
Thank you, guys.
I believe you should replace:
var uri = Uri.parse('https://demo.com/rest/v1/default/products');
uri = uri.replace(queryParameters: params);
print(uri);
with:
var uri = Uri.https('demo.com', '/rest/v1/default/products', params);
more on this: Uri.https
more on: replace
example result:
regardless of this, if I try with your params, the library behaves normal and encodes the special characters. (see more here)
if we put the actual request in the browser to check the response:
https://demo.mage-mobile.com/rest/v1/default/products?searchCriteria[filter_groups][0][filters][0][condition_type]=in&searchCriteria[filter_groups][0][filters][0][field]=type_id&searchCriteria[pageSize]=20&searchCriteria[filter_groups][0][filters][0][value]=simple%2Cconfigurable%2Cbundle&searchCriteria[currentPage]=1&searchCriteria[sortOrders][0][field]=created_at&searchCriteria[sortOrders][0][direction]=DESC
we get the following response:
And this brings me to my initial suspicion: the API does not support this call.
Maybe you should also check this type of param from your code: 'searchCriteria[filter_groups][0][filters][0][condition_type]', it seems you are trying to acces some information from a collection but you actually writing a string...
try removing the quotes (' bla bla ') from these params id... also try to put the request direcly in the browser(or postman) to see it work.
About the encoding (changing [ to %5B) -- this is normal and it should happen.
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());
}
I have an interface in my application that maintains properties that I want to send to my database, as well as properties that I do not.
Specifically I maintain an property called state that can be set to open or null (closed) which then triggers Angular2's Animation state function. I use this in *ngFor lists to open an close a panel of information about the item.
However, I don't want to store the value of state in my database since it always defaults to null. Currently, I pass the whole object to the http call so the state property gets sent too. How can I instead ignore it?
pushItemToDay(item: any, dateStr: Date): void {
let body = JSON.stringify(item);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
this.http.post(this.baseURL + 'api/addItem/' + dateStr, body, options)
.toPromise()
.catch(this.handleError);
}
Delete can do damage if the object is used after the post. The function stringify has an additional parameter exactly to ignore unwanted entries.
let source = {
'meal': 'burger',
'milkshake': 'chocolat',
'extra':'2 hot dogs',
'free': 'smile'
};
let ignoreList = [ 'meal', 'extra' ];
function replacer(key,value)
{
if (ignoreList.indexOf(key) > -1) return undefined;
else return value;
}
let data = JSON.stringify(source, replacer);
console.log(data);
Alright, so I have an image at a specific URL with the variable path, I want to download it and store it in CollectionFS. How can I get/create the image buffer from the response?
var request = Npm.require('request').defaults({encoding: null});
request.get(path, function(err, res, body)
{
return CollectionFS.storeBuffer(res.request.uri.path, body, {
});
});
It appears to store successfully, with the correct size. But when I try to view the image it appears to be corrupted.
Answering my own question. I had two issues with the above code. Firstly, meteor doesn't like it when you try to touch the database inside of a callback, so I added a future to wait until the callback was done.
Secondly, the default encoding on storeBuffer is utf-8 - which is a problem for images. Changing it to ascii solved my problem.
var Future = Npm.require("fibers/future");
var pre = new Future();
var preOnComplete = pre.resolver();
var request = Npm.require('request').defaults({encoding: null});
request.get(path, function(err, res, body)
{
return preOnComplete(err, res, body);
});
Future.wait(pre);
return EventImages.storeBuffer(pre.value.request.href, pre.value.body, {
contentType: 'image/jpeg',
metadata: { eventId: eventId },
encoding: 'binary'
});