http Dart package examples are outdated, how to use client.get() - flutter

Here's the second example given by the http package: https://pub.dev/packages/http
var client = http.Client();
try {
var uriResponse = await client.post('https://example.com/whatsit/create',
body: {'name': 'doodle', 'color': 'blue'});
print(await client.get(uriResponse.bodyFields['uri']));
} finally {
client.close();
}
I get error: uriResponse.bodyFields['uri'] no such method.
I can see that there's no property named bodyFields in the class Response: https://pub.dev/documentation/http/latest/http/Response-class.html
So how should I use the client.get()?
I checked the docs for the function https://pub.dev/documentation/http/latest/http/get.html and I wrote this:
print(await client.get(uriResponse.request.url, {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36',
}));
But this also fails with error:
Class 'IOClient' has no instance method 'get' with matching arguments.
E/flutter (19613): Receiver: Instance of 'IOClient'
E/flutter (19613): Tried calling: get(Instance of '_SimpleUri', Instance of '_CompactLinkedHashSet<Map<String, String>>')
E/flutter (19613): Found: get(dynamic, {Map<String, String> headers}) => Future<Response>

write your post as below and print the response separate.
final response = await client.post(
'*endPoint url*',
headers: *headers if you have any*,
body: jsonEncode({'name': 'doodle', 'color': 'blue'}
));
print(json.decode((response.body)));
and follow the same structure for the get method as well.

String url = "url";
Response response = await client.get(url);
print('Response status: ${response.statusCode}');
print('Response body: ${json.decode((response.body))}');

Related

how post api with authentication identifier and secret in flutter

i want fetch data by post method with identifier and secret in flutter
where should i add "identifier" and "secret" in post method?
in postman they added to body and that works but i couldnt add these to flutter code:
Future post(String url, var data) async {
String url = 'https://member.example.com/includes/api.php';
var data = {
'identifier': 'identifier code otm7LE8OzlBmprXn',
'secret': 'secret code SXZgmDpX8miT31PSRQ',
'action': 'GetInvoices',
'userid': 6414,
'orderby': 'date',
'responstype': 'json',
};
try {
final response = await http.post(
Uri.parse(url),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
'Accept': 'application/json',
},
body: jsonEncode(data),
);
} catch (e) {
print(e);
}
}
E/flutter ( 6118): result=error;message=Authentication Failed

Make a post HTTP

I follow the below code, but it seems not to work:
var body = jsonEncode(<String, String>{
'uid': uid,
'limit': '10',
'offset': '2',
'action': 'feed',
});
final response = await http.post(
Uri.parse('http://abc.or/fb/selectPosts.php'),
body: body,
);
if (response.statusCode == 200) {
List<Post> posts = [];
// If the server did return a 200 OK response,
// then parse the JSON.
print((jsonDecode(response.body)));
return List<Post>.from(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to update album.');
}
My API looks like this: http:/abc.or/fb/post.php?uid=aaaa&limit=10&offset=2&action=feed
try this.
import 'package:http/http.dart';
...
static const urlPrefix = 'https://jsonplaceholder.typicode.com';
...
Future<void> makePostRequest() async {
final url = Uri.parse('$urlPrefix/posts');
final headers = {"Content-type": "application/json"};
final json = '{"title": "Hello", "body": "body text", "userId": 1}';
final response = await post(url, headers: headers, body: json);
print('Status code: ${response.statusCode}');
print('Body: ${response.body}');
}
Those are query fields not request body fields.
They are passed in the link or as queryparematers in a Uri
final response = await http.get(
Uri(
path: <your url without the queries(http://abc)>,
query: <Your queries as they are in the string (uid=aaaa&limit=10&offset=2&action=feed), you can use string interpolation to fix the values in or better still use queryparematers, not both>
queryParameters : <String, dynamic>{ 'uid': uid, 'limit': 10, 'offset': 2, 'action': feed },)
);
I use a get method which should be the standard for such url. Do confirm from whoever wrote the api if it is a uses a get or post method.

Flutter http - Invalid argument(s): Invalid request body when jsonEncode is used

Future<void> _sendData() async {
final url = Uri.https('websitename.tld', 'restricted/login');
try {
final response = await http.post(
url,
headers: {"Content-Type": "application/json"},
body: {
json.encode({
'username': 'UserName',
'userpass': 'UserPaZZw0rd',
})
},
);
} catch (err) {print(err);}
}
causes : flutter: Invalid argument(s): Invalid request body "{{"username":"UserName","userpass":"UserPaZZw0rd"}}".
if i make a call without json, code works like a charm.
jsonEncode instead of json.encode -> same result.
Any ideas?
Thanks!
Try this.
body: json.encode({
'username': 'UserName',
'userpass': 'UserPaZZw0rd',
}),

Flutter - How to send a POST request using HTTP in Dart?

I am using an API that converts HTTP to JSON and to get a response from the server I need to send a post request of HTML however i'm not sure how to do that?
This is my current implementation -
Future<String> test() async {
var link =
await http.get('https://example.com');
var body = parse(link.body);
return body.outerHtml;
}
Future<Album> createAlbum(String html) async {
final http.Response response = await http.post(
'https://www.html2json.com/api/v1',
headers: <String, String>{
'Content-Type': 'text/html; charset=UTF-8',
},
body: html,
);
if (response.statusCode == 200) {
return Album.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to create album.');
}
}
I call this is when my app starts like so,
#ovveride
void initState() {
test().then((body) => createAlbum(body)); //Output returns HTTP error 301, am I doing something wrong?
super.initState();
}
Checked the following code which worked for me.
Future<Album> createAlbum(String html) async {
final http.Response response = await http.post(
'https://www.html2json.com/api/v1',
headers: <String, String>{
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
},
body: html,
);
You need to change the Content-type to application/x-www-form-urlencoded; charset=UTF-8. This should do the trick.
Thanks to DARSH SHAH, I solved this using dio (https://pub.dev/packages/dio).
dynamic response;
Dio dio = Dio();
Future<dynamic> test() async {
dynamic link = await dio.get(
'https://example.com');
return link;
}
Future<dynamic> post(dynamic body) async {
String _baseUrl = "https://html2json.com/api/v1";
var options = Options(
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
followRedirects: false,
);
final response = await dio.post(
_baseUrl,
data: body,
options: options,
);
return response;
}
FloatingActionButton(
onPressed: () async {
dynamic responseHTML = await test();
response = await post(responseHTML.data); //This will contain the JSON response
},
);

How to fix errors on http put request on flutter

I'm trying to authenticate using the below code and unable to succeed. It looks like the json structure is incorrect.
I've tried to check the same on native android using kotlin and it works correctly.
below are the logs
flutter: {data: {email: nelloresec#xxx.com, password: xxx}}
flutter: "{\"errors\":[]}"
flutter: http://xxx.xxx.xx
flutter: Instance of 'Response'
flutter: 400
flutter: {errors: []}
The default content-type for a body of types String, List<int> or Map<String, String> is 'text/plain' and I guess you want 'application/json'
In addition you can directly pass in the user object to the body paramater (as toJson will be invoked automatically by the json.encode()-function).
Lastly, you don't need to use both await and .then(...), await will suffice:
void userLogin(String url, User user) async {
http.Response response = await http.put(
'$url/api/login',
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
},
body: json.encode(user),
);
if (response.statusCode == 200) {
print(url);
print(response.statusCode);
print(json.decode(response.body));
} else {
print(json.encode(response.body));
print(url);
print(response);
print(response.statusCode);
print(json.decode(response.body));
throw Exception("Error while fetching data");
}
}