flutter get request with parameter - flutter

I am using Client() from http.dart. I am able to post with parameter but I have no idea how to do get with parameter. Post has body that takes the parameter but get doesn't.
I have tried
This is my client
Client httpClient = Client();
var response = await httpClient.get("controller/action/{parameter here}"

I hope this should solve your problem
fetchData() async {
Client httpClient = Client();
counter++;
var response =
await httpClient.get('https://jsonplaceholder.typicode.com/photos/$counter');
print(response.body);
}

i think you are saying that you want any kind of data to be sent to the server with GET request too,
you can not do it simply,
may be your parameter are the header of the Get ,
try passing your parameters in the header of GET

Related

Calling API from Saleforce is giving error code 500

I have a REST API to callout from Salesforce.
The authorization of the API is through access token.
I am able to get the access token through POST request in Salesforce. Also tested from Postman through that token and able to get a successful response.
I am using the below code to callout the API using the access token:
String endpoint_x = '*****';//Putting my endpoint here
Http httpObject;
HttpResponse response;
String accessToken;
accessToken = MyUtilityClass.getAccessToken();
jsonBody = json.serializePretty('', true);//Yes, My JSON is empty
HttpRequest request = new HttpRequest();
request.setEndpoint(endpoint_x);
request.setHeader('Authorization', 'Bearer '+accessToken);
request.setMethod('POST');
request.setBody(jsonBody);
httpObject = new Http();
response = httpObject.send(request);
System.debug('Response=' + response);
Getting Response value as below:
System.HttpResponse[Status=Internal Server Error, StatusCode=500]
I have tried putting '{}' in the Jsonbody. Added 'Content-Type' in header but nothing worked.
Where should I lookout for this?
In the Postman, I was not putting anything in the body, and getting a successful response.
To get the same behaviour, I was using empty string in Apex, like this:
jsonBody = json.serializePretty('', true);
But the parser was not working correctly.
To solve this, I created a class without any field:
class ClassForEmptyBody{
}
And used object of that class in the serializer:
ClassForEmptyBody classForEmptyBodyObject = new ClassForEmptyBody();
jsonBody = json.serializePretty(classForEmptyBodyObject , true);
Why are you passing json body if nothing is in there. Just skip setbody code and try.

How display data which comes from async function?

I use api for get information which need to be display
Future <String> Get_Amount_Jackpot() async {
// SERVER LOGIN API URL
var url2 = 'https://www.easytrafic.fr/game_app/get_jackpot_lotto.php';
// Starting Web API Call.
var response2 = await http.get(url2,headers: {'content-type': 'application/json','accept': 'application/json','authorization': globals.token});
// Getting Server response into variable.
Map<String, dynamic> jsondata2 = json.decode(response2.body);
return jsondata2["value"];
}
I call it here :
void initState() {
ListLotto = Grille_display();
jackpot = Get_Amount_Jackpot();
super.initState();;
}
How i can display the value "jackpot" which is a simple number on mobile screen. Note i use futurebuilder for another api request, this is why it is complicated. Normally i use futurebuilder for display async data but there i need 2 différents api request so 2 futureBuilder ??? Is it possible and how do that ?
You can use then to get the returned value from the function.
Get_Amount_Jackpot().then((value){
//value is what is returned from the function
jackpot = value;
});
I'm not sure if you can use uppercase letter as the start of a function name, but i copied your function name for my answer. Hope this helps.

flutter await GET response is not working

i have the follow function:
Future<Null> _loadORDER(String menssage) async {
var enZona =await ApiClient.zonaNum(menssage, apiKey);
print('enZona: $enZona');
if (enZona == 'true') {
_moveToNotification(context);
};
}
the print give me the follow message: "enZona: Instance of 'Response'"
if i test the response from postman of the api query is working normally and give me: true ,
then i hope that the print result will be : "enZona: true"
but i don't know how i do to wait the response of the ApiClient before continue with the conditional (if)
thanks for your help!
thanks i add the .body but i get the same response, the apiclient code is the follow:
final response = await http.get(baseUrl + '/shop/order/$message',
headers: {HttpHeaders.authorizationHeader: apiKey});
print("enZona: $response.body");
return response;
the print value for this is: enZona: Instance of 'Response'.body
You should do print("enZona: ${response.body}"); with the curly bracket, or you can assign response.body to some variable first.
final foo = response.body; print(foo);
If you go to the pub.dev documentation for the Response class, you will see that Response is more than the content of the response. It is a wrapper class that also includes information such as the statusCode of the response, the headers, etc.
When you saw the response in Postman, you only cared about the content of the response, that is, the body of the response. What you are looking for in your code is not the enZona instance of Response, but the body of the enZona response.
Therefore, you have to swap enZona by enZona.body when trying to access the contents of your response.

How to get query params in a server request in flutter?

In order to authenticate with Imgur on a mobile app, I decided to spawn an http server on port 8585 in order to complete the oauth flow. The request is read and a response is written, but I cannot access the queryparameters from the url.
I already tried using uri.queryparameters["access_token"], but null is returned.
the server is spawned as follows:
Future<Stream<String>> _server() async {
final StreamController<String> onCode = new StreamController();
HttpServer server =
await HttpServer.bind(InternetAddress.loopbackIPv4, 8585);
server.listen((HttpRequest request) async {
print(request.uri.hashCode);
final String accessToken = request.uri.queryParameters["access_token"];
request.response
..statusCode = 200
..headers.set("Content-Type", ContentType.html.mimeType)
..write("<html><h1>You can now close this window</h1></html>");
await request.response.close();
await server.close(force: true);
onCode.add(accessToken);
await onCode.close();
});
return onCode.stream;
}
the url the server gets is of the sort: http://localhost:8585/callback#access_token=your_token_here&expires_in=315360000&token_type=bearer&refresh_token=_your_refresh_token_here
Can anyone help me? I've been stuck on this for two whole days!
It returns null because query parameters start with ? at the beginning but in this link, there is a # before the query parameters and replacing it with a ? does solve the problem.
solution 1:
var uri =Uri.parse('http://localhost:8585/callback#access_token=your_token_here&expires_in=315360000&token_type=bearer&refresh_token=_your_refresh_token_here');
var newUri = Uri(query: uri.toString().substring(uri.toString().indexOf('#')+1));
print(newUri.queryParameters['access_token']) // your_token_here;
solution 2:
var uri =Uri.parse('http://localhost:8585/callback#access_token=your_token_here&expires_in=315360000&token_type=bearer&refresh_token=_your_refresh_token_here');
var newUri = Uri.parse(uri.toString().replaceFirst('#', '?'));
print(newUri.queryParameters['access_token']) // your_token_here;

Verify API Response

Am getting the response of a request like this:
var response = command.PostCommand(testCommand);
I will like to validate that the response is in a json format so am doing it like this:
Assert.AreEqual("application/json", response.ContentType);
Is this way correctly or do i need to specifically validate it from the content-type header response?
You can use the IRestRequest.OnBeforeDeserialization callback to check the response content type before it gets deserialised:
var request = new RestRequest(url)
.AddQueryParameter(x, y); // whatever you need to configure
request.OnBeforeDeserialization =
response => CheckContentType(response.ContentType);
await client.PostAsync<MyResponse>(request);