I have code like this:
Future<http.Response> makeRequest() async {
return await http.get(Uri.parse(url));
}
my "url" is a string, and it is working. From the internet i got string like "10" or "125", but when i use this method in my project and im converting it to string it only writes me an error:
Instance of 'Future Response'
, how can i take my string from the internet?
this is my url:
https://apialgorytm20210606150610.azurewebsites.net/algorytm/5w5
Future<String> getObjectFromAPI() async {
var response = await http.get(Uri.parse('www.myAPI.com/getData'),); //1
if (response.statusCode == 200) { //2
return(jsonDecode(response.body)["yourObjectHere"]); //3
} else {
return 'error';
}
}
Here you go.
Put your API url in line 1.
Line 2 checks if you receive a 200OK return or some kind of error code. Line 3 prints the decoded JSON response from the API, and you can enter the specific object you want to fetch as well
Future makeRequest() async {
var res= await http.get(Uri.parse(url));
If(res.statusCode==200){
print(res.body);
return res.body;}else{return null;}
}
now use the above function
var data=makeRequest();
print(data);
Related
I have this design, I created it and put the data manually, the question is how can I get the data in the image and it is from this website (https://jsonplaceholder.typicode.com/posts) and display it in the same design
var url = Uri.parse("https://jsonplaceholder.typicode.com/posts");
var response = await http.get(url);
if (response.statusCode == 200) {
var responseJson = jsonDecode(response.body);
responseJson as List;
return responseJson.map((e) => YourModel.fromJson(e)).toList();
}
Firstly, you can paste your JSON in the link below, click convert and get your Dart classes for free.
Secondly, you can copy the result which is named JsonPlaceHolderResponse and create a new file in your project, and paste the result there.
Finally, you can use this code to get your data from defined API:
import 'package:http/http.dart';
Future<JsonPlaceHolderResponse?> getData(String url) async {
final _response = await Client().get(
url
);
if (_response.successResponse) {
final _json = jsonDecode(_response.body);
return JsonPlaceHolderResponse.fromJson(_json);
} else {
return null;
}
return null;
}
extension ResponseExtension on Response {
bool get hasWrongCredentials => statusCode == 422;
bool get tooManyRequests => statusCode == 429;
bool get successResponse => statusCode >= 200 && statusCode < 300;
}
My requirement is need to make get rest api call in flutter.my code is as below
final url = "https://app2.sas.com/uh/device/1890/publicKey";
https://app2.sas.com/ is my base url followed by api end point
should i need to add any certificate for https://app2.sas.com/ to work?
void getPublickey() async {
print('getPublickey');
try {
final response = await http.get(Uri.parse(url));
final jsonData = jsonDecode(response.body);
if (response.statusCode == 200) {
print(jsonData.toString());
} else {}
} catch (err) {
print(err.toString());
}
}
when i hit above api i m getting below response, please let me know any mistake i m doing above?
I/flutter ( 4017): {code: 404, message: HTTP 404 Not Found}
Any help is appreciated
try
Future <void>
instead of void and remove http
Future getPublickey() async {
print('getPublickey');
try {
final response = await get(Uri.parse(url));
final jsonData = jsonDecode(response.body);
if (response.statusCode == 200) {
print(jsonData.toString());
} else {}
} catch (err) {
print(err.toString());
}
}
I don't think the problem is from Flutter. Trying out your URL https://app2.sas.com/uh/device/1890/publicKey returns a 404 too.
You should double-check the URL and make sure the endpoint is correct.
You should probably be returning the string public key:
Future getPublickey() async {
print('getPublickey');
try {
final response = await http.get(Uri.parse(url));
final jsonData = jsonDecode(response.body);
if (response.statusCode == 200) {
print(jsonData.toString());
return jsonData;
} else {
print(response.statusCode);
return null;
}
} catch (err) {
print(err.toString());
return null;
}
}
I want to pass base64Encode string to my web API. I could encode image and pass base64Encode string to my api but i got "Request-URI Too Long" message from API.
how can i solve this problem ?
static Future<AskModel> addArticle(String title, String content, String base64Image) async {
var url = Uri.http(Config().baseUrl, Config().baseUrlPathAddArticles, {
'title': title,
'content': content,
'base64Image': base64Image,
});
var response = await http.post(url);
if (response.statusCode == 200) {
var jsonString = response.body;
return askModelFromJson(jsonString);
} else {
return null;
}
}
As your using a POST method, so you can set your title,content and base64Image in the body instead of in the url : https://flutter.dev/docs/cookbook/networking/send-data#2-sending-data-to-server
I'm trying to get a "File was uploaded." string back from a successful Future HTTP post request so that I can create a SnackBar but all I get back from the return is null. Here's the button which calls the Future;
IconButton(
icon: Icon(TriangleAll.upload_3, ),
onPressed: () async {
replyresult = await uploadReply(
filepath: _current.path);
)
if (replyresult != null){
print(replyresult);
}
}
)
And here's the code for the future;
Future<String> uploadReply(
}) async {
final serverurl = "http://example.com/example.php";
final filepath = "examplefilepath";
String serverResponse;
var request = http.MultipartRequest('POST', Uri.parse(serverurl));
var multiPartFile = await http.MultipartFile.fromPath("audio", filepath,
contentType: MediaType("audio", "mp4"));
request.files.add(multiPartFile);
request.send().then((result) async {
http.Response.fromStream(result).then((response) {
if (response.statusCode == 200) {
serverResponse = response.body;
print(serverResponse);
return serverResponse ;
}
});
});
}
I'm trying to use the replyresult variable to create the snackbar upon a successful 200 server response. I know the post is successful as I can see the correct printed serverResponsein the console.
I've tried to simply do;
return response.body ;
But I'm still getting null at the replyresult variable.
because the method returns before the response arrives in Future, do this
var response = await http.Response.fromStream(result);
if (response.statusCode == 200) {
serverResponse = response.body;
print(serverResponse);
return serverResponse ;
} else return '';
or a single await ahead of the Future.
This is what worked.
var multiPartFile = await http.MultipartFile.fromPath("audio", filepath,
contentType: MediaType("audio", "mp4"));
request.files.add(multiPartFile);
final response = await http.Response.fromStream(await request.send());
String serverResponse;
if (response.statusCode == 200) {
String serverResponse = response.body;
print(serverResponse);
return serverResponse;
}
String url = 'http://localhost:9000/user/john.doe#email.com';
Future<String> get makeRequest() async {
var response = await http
.get(Uri.encodeFull(url), headers: {"Accept": "application"});
print(response.body);
}
I get an error on makeRequests() that says "This function has a return type of 'Future', but doesn't end with a return statement."
You have to return data corresponding to the return type of the function.
String url = 'http://localhost:9000/user/john.doe#email.com';
Future<String> get makeRequest() async
{
var response = await http.get(Uri.encodeFull(url), headers: {"Accept": "application/json"});
print(response.body);
return(response.body);
}
You must return a String in the function with the header Future< String >. You probably want to return response.body