In Flutter "final response = await http.get(url);" I am getting an error in the url part of the code - flutter

I am getting an error in the url part of the code, I have shown the error in the screenshot. How can I fix my code without changing its function.
Future<List<Articles>?> getNews() async {
String url = "https://jsonplaceholder.typicode.com/posts";
final response = await http.get(url);
if (response.body.isEmpty) {
final responseJson = json.decode(response.body);
News news = News.fromJson(responseJson);
return news.articles;
}
return null;}

You need to pass Uri instead of string.
final response = await http.get(Uri.parse(url));

You can assign uri something like this
var uri= Uri.https('jsonplaceholder.typicode.com', 'posts');
And if you want to add queryparametrs then use below code
final queryParameters =
{
'key' : 'value',
};
var uri= Uri.https('jsonplaceholder.typicode.com', 'posts',queryParameters);
And use this uri in place of Url.
final response = await http.get(uri);

Related

How to make a http post using form data in flutter

I'm trying to do a http post request and I need to specify the body as form-data, because the server don't take the request as raw or params.
here is the code I tried
** Future getApiResponse(url) async {
try {
// fetching data from the url
final response = await http.get(Uri.parse(url));
// checking status codes.
if (response.statusCode == 200 || response.statusCode == 201) {
responseJson = jsonDecode(response.body);
// log('$responseJson');
}
// debugPrint(response.body.toString());
} on SocketException {
throw FetchDataException(message: 'No internet connection');
}
return responseJson;
}
}
but its not working. here is the post man request
enter image description here
its not working on parms. only in body. its because this is in form data I guess.
how do I call form data in flutter using HTTP post?
First of all you can't send request body with GET request (you have to use POST/PUT etc.) and you can use Map for request body as form data because body in http package only has 3 types: String, List or Map. Try like this:
var formDataMap = Map<String, dynamic>();
formDataMap['username'] = 'username';
formDataMap['password'] = 'password';
final response = await http.post(
Uri.parse('http/url/of/your/api'),
body: formDataMap,
);
log(response.body);
For HTTP you can try this way
final uri = 'yourURL';
var map = new Map<String, dynamic>();
map['device-type'] = 'Android';
map['username'] = 'John';
map['password'] = '123456';
http.Response response = await http.post(
uri,
body: map,
);
I have use dio: ^4.0.6 to create FormData and API Calling.
//Create Formdata
formData = FormData.fromMap({
"username" : "John",
"password" : "123456",
"device-type" : "Android"
});
//API Call
final response = await (_dio.post(
yourURL,
data: formData,
cancelToken: cancelToken ?? _cancelToken,
options: options,
))

flutter http get request with parameters

I want to send a GET http request with parameters, my problem is that when I add the parameters in the request URL manually it works fine, but when I pass them as parameters it returns an exception without any explanation and somehow the execution stops after Uri.https
here is the code that I want to achieve
Future<List<LawFirm>> getLawFirms () async {
Map<String, dynamic> parameters = {
'total': true
};
final uri =
Uri.http('www.vision.thefuturevision.com:5000',
'/api/law-firm', parameters);
final response = await http.get(uri);
var dynamicResponse = jsonDecode(response.body);
totaLawFirms = await dynamicResponse['total'];
var lawFirms = await dynamicResponse['data'];
List<LawFirm> list = List<LawFirm>.from(lawFirms.map((x) => LawFirm.fromJson(x)));
print(list);
notifyListeners();
return list;
}
and here is the manual way which shouldn't be applied
final response = await get(Uri.parse('$baseURL/law-firm?total=true'));
I have also tried the dio library from pub.dev but also wasn't helpful.
And finally thanks in advance to everyone
You may try this
Map<String, dynamic> parameters = {
'total': true
};
var uri = Uri(
scheme: 'http',
host: 'www.vision.thefuturevision.com:5000',
path: '/law-firm',
queryParameters: parameters,
);
final response = await http.get(uri);
import 'package:http/http.dart' as http;
final response =
await http.get(Uri.parse("${Constants.baseUrl}endpoint/param1/param2"));
Just modify your GET request like this.
Try this
import 'package:http/http.dart' as http;
callAPI() async {
String login = "sunrule";
String pwd = "api";
Uri url = Uri.parse(
"http://vijayhomeservices.in/app/api/index.php?apicall=login&login=$login&password=$pwd");
final response = await http.get(url);
if (response.statusCode == 200) {
final body = json.decode(response.body);
print(body.toString());
} else {
throw Exception("Server Error !");
}
}
Query parameters don't support bool type. Use String instead: 'true'.
A value in the map must be either a string, or an Iterable of strings, where the latter corresponds to multiple values for the same key.
Map<String, dynamic> parameters = {'total': 'true'};
final uri = Uri.http(
'www.vision.thefuturevision.com:5000', '/api/law-firm', parameters);
print(uri); // http://www.vision.thefuturevision.com:5000/api/law-firm?total=true
See Uri constructor for details.

Flutter : get the original link of shorten url

I have to fetch some url link, but the link is shorten like "shorturl.at/cpqCE".
I want to get the original link url in flutter.
How can I do this?
in Phph I found this :
function expandShortUrl($url) {
$headers = get_headers($url, 1);
return $headers['Location'];
}
// will echo https://deluxeblogtips.com
echo expandShortUrl($url);
Thanks to #RandalSchwartz I solved it by using :
getUrl(url) async {
final client = HttpClient();
var uri = Uri.parse(url);
var request = await client.getUrl(uri);
request.followRedirects = false;
var response = await request.close();
while (response.isRedirect) {
response.drain();
final location = response.headers.value(HttpHeaders.locationHeader);
if (location != null) {
uri = uri.resolve(location);
request = await client.getUrl(uri);
// Set the body or headers as desired.
if (location.toString().contains('https://www.xxxxx.com')) {
return location.toString();
}
request.followRedirects = false;
response = await request.close();
}
}
}
you can also do it by just sending a normal post request with the short link and you will then get the response which includes the original/full URL.
e.g
var uri = Uri.parse(shortUrl);
try {
var response = await http.post(
uri,
headers: {"Accept": 'application/json'},
);
// with below code you get the full path of a short url
String fullPath = response.headers.entries.firstWhere((element) => element.key == "location").value;
print(fullPath);
} catch (e) {
print(e);
}
hope this can help your problem.

Flutter type '_SimpleUri' is not a subtype of type 'String' error

This is my simple code
try{
final dynamic headers = await _getReqHeader();
http.Response res = await http.get(Uri.parse(url), headers: headers);
print("Dres2="+res.toString());
return _result(res);
}catch(e){
print("Dres3="+e.toString());
return _result({});
}
This code works well. But when use some url's I get type '_SimpleUri' is not a subtype of type 'String' error. In postman this url works perfectly. I could not find any information about _SimpleUri. How can I solve this problem?
The get method of the http package takes Uri.https(hostUrl , apiEndpoint) not Uri.parse.
The error appears because a simple URLs being passed to it. To fix this, you have to do this:
http.Response res = await http.get(Uri.https(host, url), headers: headers);
I had a similar issue and that's how I solved it.
static const baseUrl = "apihost.com";
Future<http.Response> _get(String url, {host = baseUrl}) async {
final header = <String, String>{};
return http.get(Uri.https(host, url), headers: header);
}
Future<String?> getData() async {
final response = await _get("/endpoint");
if (isSuccessful(response)) {
final json = jsonDecode(response.body);
} else {
print('GET failed [${response.statusCode}]:
${response.body}');
return null;
}
}

How can I use the returned value of data I got from my shared preference json file as a parameter

how can i use this as my url parameter
userData['UserName']
I have json data in my shared preference file. So I tried to get the username
of the signed in user because I want to use as a parameter to an endpoint.
I can print the username quite ok on the console but when tried to add it
on the link, the statusCode response I get is:
null.
E/flutter ( 906): Receiver: null
E/flutter ( 906): Tried calling: []("UserName")
please how can I extract his username and add it to the endpoint:
Here's the endpoint that shared preference snippet that gives me the
username:
var q;
var userData;
void _getUserInfo() async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
var userJson = localStorage.getString('loginRes');
user = json.decode(userJson);
setState(() {
userData = user;
});
print(userData['UserName']);
}
and this is where I want to use it, on the get request link below:
Future<void> get_farmer_eop() async {
final response = await http.get(
'http://api.ergagro.com:112/GenerateFarmersEop?farmerBvn=${widget.result}&dcOid=${widget.dc_result}&agentName=${userData['UserName']}',
headers: _setHeaders());
print('${response.statusCode}popo');
if (response.statusCode == 200) {
final jsonStatus = jsonDecode(response.body);
setState(() {
q = jsonStatus['Eop'];
});
print('trandid');
print('${q['TransId']}kukuk');
} else {
throw Exception();
}
}
_setHeaders() => {
'Content-type': 'application/json',
'Accept': 'application/json',
};
But on the console I print the username and if I tried to hardcode the agentName which is the username parameter example agentName=johndoh it works but when userData['UserName'] I keep getting null please can anyone help me?
If _getUserInfo not returning anything then why to create a separate method, try below code. It should work.
Future<void> get_farmer_eop() async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
var userJson = localStorage.getString('loginRes');
user = json.decode(userJson);
final response = await http.get(
'http://api.ergagro.com:112/GenerateFarmersEop?farmerBvn=${widget.result}&dcOid=${widget.dc_result}&agentName=${user['UserName']}',
headers: _setHeaders());
You are using a wrong formatted url, try this instead:
final response = await http.get(
"http://api.ergagro.com:112/GenerateFarmersEop?farmerBvn=${widget.result}&dcOid=${widget.dc_result}&agentName=${userData['UserName']}",
headers: _setHeaders());