I'd like to get you'r advice on this one.
Suppose I want to handle the errors/status codes I get from POST or GET methods in http protocol, I tried to implement something like this:
class Login extends IRequest<Map<String, dynamic>> {
Login(var email, var password) {
var data = {'email': email, 'password': password};
var url = API_PREFIX + LOGIN_ENDPOINT;
var body = json.encode(data);
var headers = {
'Content-type': CONTENT_TYPE,
};
}
Future<IResponse> login(var mail, var password) async {
final response = await http.post(url, headers: headers, body: body);
switch (response.statusCode) {
case OK:
case ACCEPTED:
final responseJson = json.decode(response.body);
String key = responseJson['login_key'];
String experial = responseJson['experial'];
var token = LoginToken(key, experial);
return token;
case NOT_FOUND:
return ErrorResponse(response.statusCode.toString());
}
}
}
I'm doing the request in an async way, and then check for the response code, but there are many cases to choose from , starting from 200 up to 500, which makes the code very messy and ugly,
Is there any easy way to work around this?
I have though about try / catch, but is it usable in this situation? (I know try catch are for exceptions, and here I just want the status code of the result...)
If you will take a look at the wiki you can see, that codes are divided into groups. 1xx means informational response, 2xx success and others.
With switch statement you can check, to which group received code belongs and continue or throw an error.
Other option is to add interceptors, and check response codes there.
Related
I want to print BTC conversion to other currencies. I am using bitcoinaverage. On the browser, the URL is not working. The screen displays this "Unauthenticated requests are not allowed. Take out a new plan or start a free trial at https://pro.bitcoinaverage.com". I am using Flutter. On console, it is giving a 404 error. The following is the code snippet.
const bitcoinAverageURL = 'https://apiv2.bitcoinaverage.com/indices/average/ticker';
Future getCoinData(String selectedCurrency) async {
var authKey = '$bitcoinAverageURL/BTCAUD';
http.Response response = await http.get(Uri.parse(authKey));
if (response.statusCode == 200) {
var decodedData = jsonDecode(response.body);
double current = decodedData['last'];
return current.toStringAsFixed(0);
} else {
print(response.statusCode);
throw 'Problem with get request';
}
From documentation:
All requests to our API must be authenticated with your public key.
You need to autrhorize on API site and get your API access token. API usage described in Official documentation.
Try to add your API key to header:
await http.get(
Uri.parse(url),
headers: {
'x-ba-key': 'your_api_key',
},
);
Just before login in the user, I need to test if the WebServce respond then if the system is in maintenance. On the WebService part (core3 .net) I got 2 functions:
HeartBeat that return: return Ok("OK");
MaintenanceInfo that return Return OK("No");
I display in real time the result of the 2 tests and if no problems, I display the login panel.
I need to do these tests in sequence, I was thinking doing it with await operator.
I got a TestHelperServie class with 2 functions that return bool. But I can't find how to pass from a HTTP subscribe function to a bool result. With true if I got the OK response and false if I got a timeout or another fail HTTP.
For now I do this:
async TestHeartBeat()
{
let Response:Boolean = false;
const headers = new HttpHeaders()
.set('Content-Type','application/json');
const options = {
headers: headers,
observe: "response" as const,
responseType: "json" as const
};
await this.http.get(`${environment.apiUrl}/TestController/HeartBeat`, options)
.subscribe(res=>{
Response = true;
},
error=>{
Response = false;
})
return Respone;
}
But the function does not wait for the http response.
How can I fix this?
Sorry for my newbies question, but I came from the c# world and we use await/async a lot. I don't think I can do that the same way in angular 10.
You can not await on Observables, you have to convert it to promise using toPromise()
return await this.http.get(....).toPromise().then(res=> Response = true).catch(err => Response = false);
Use rxjs pipe, map and catchError.
async TestHeartBeat()
{
const headers = new HttpHeaders()
.set('Content-Type','application/json');
const options = {
headers: headers,
observe: "response" as const,
responseType: "json" as const
};
return await this.http.get(`${environment.apiUrl}/TestController/HeartBeat`, options)
.pipe(
map(res => true),
catchError(error => false)
).toPromise();
}
Now you can call it like the following:
if (await TestHeartBeat()) {
// Display your panel
} else {
// Service is in maintenance
}
Im a newbie to flutter so please if you think the question context is wrong update it, im fetching a data from an SQl server to my flutter app, and i also want to send the users info back to the server after they fill out a form, im using the http.post and i get the response’s body correctly but when i open the Server Url (api url) i dont see it updated with the new info i posted to it, can someone please tell me how Post is supposed to work?
I'm new to Flutter too, this is a working example of how i understand it
class HttpService {
createUser(String name, String lastname) async {
Map data = {'name': name, 'lastname': lastname};
var body = json.encode(data);
var jsonResponse = null;
var response = await http.post(serverUrl + "/create/",
headers: {
HttpHeaders.authorizationHeader: '**Token_here_if_you_use_it**',
HttpHeaders.contentTypeHeader: "application/json",
}, body: body);
jsonResponse = json.decode(response.body);
if (response.statusCode == 201) {
jsonResponse = json.decode(response.body);
if (jsonResponse != null) {
print(jsonResponse.toString());
}
} else {
print(jsonResponse.toString());
}
}
}
In your main.dart :
final HttpService httpService = HttpService();
httpService.createUser(name,lastname);
i want to consume a web service that require headers, body and parameters in future class
but the problem it shows an error "the named parameters isn't defined'
Future<http.Response> postLogin(String login, String password, String jwt) async{
final response = await http.post(Uri.encodeFull('$baseurl/mobile/login'),
headers: {
HttpHeaders.acceptHeader: 'application/json ; charset=utf-8',
HttpHeaders.contentTypeHeader:'application/x-www-form-urlencoded',
HttpHeaders.authorizationHeader :'Bearer $jwt',
},
body: bodyLoginToJson(login, password, token),
parameters: {
token, login
}
);
can someone help please
As mentioned by #jamesdlin, parameters is not a named parameter of the http class. The standard way of posting values using dart / flutter is a map past to the body parameter. Don't assume the terminology used in postman will be the same in dart.
Map<String, String> _headers = {
"Accept":"application/json"
};
var response = await http.post(LOGIN_URL, headers: _headers, body: {
"username": username,
"password": password,
// whatever other key values you want to post.
}).then((dynamic res) {
// ... Do something with the result.
});
I use video.js player with HLS.
I would like to detect HTTP response code for each failed request, which video.js makes to play a video. For example, if a response is 304 then my code needs to make a special action (show a message).
player.on('error', ...) does not provide such information. As well as tech level error.
I need something like:
player.on('request', function(response) { ... }
The best solution I found is wrapping video.xhr object with special handler.
Example of the code (using underscore.js library):
videojs.xhr = _.wrap(videojs.xhr, function(fn, options, callback) {
var wrapped_callback = _.wrap(callback, function(cb_fn, error, response) {
var args = _.rest(arguments, 1);
console.log('Error', error);
console.log('Response', response);
var res = cb_fn.apply(this, args);
return res;
});
return fn.apply(this, [options, wrapped_callback]);
});