Http request sent an empty body - flutter

This is the code for my post request:
Future<User> createUser(String name,String username,String email,String password, String passwordConfirm, String role) async {
final response = await http.post('http.register.com',
body:jsonEncode(<String, String>{
'name': name,
'username': username,
'number': email,
'password': password,
'passwordConfirm':passwordConfirm,
'role':role,
})
);
if (response.statusCode == 200) {
return User.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to load request');
}
}
The problem is once I sent it, the body goes empty to the API.How could I solve it?
_futureUser = createUser(_namecontroller.text ,_usernamecontroller.text,_email.text ,_passwordcontroller.text ,_passwordConfirmcontroller.text, _role);
I put some more codes,I think it could be helpful.

According to post function document https://pub.dev/documentation/http/latest/http/post.html
If body is String , the content-type of the request will default to "text/plain".
If body is Map , the content-type of the request will default to "application/x-www-form-urlencoded".
You can set header to application/json
code snippet
http.post(url,
headers: {"Content-Type": "application/json"},
body: body

Related

Getting empty response body from a http post request to an api

This is my code. The goal is to get the link with file id.
// body parameter
Map<String, dynamic> body = {'file_id': 123};
String jsonBody = json.encode(body);
// response request
var download_response = await http.post(
Uri.parse('https://api.opensubtitles.com/api/v1/download'),
headers: {
'Content-Type': 'application/json',
'Api-Key': 'yCTZwGASncUthpMkMkbQDjcUdrrM2r8v'
},
body: jsonBody,
);
// print
debugPrint(download_response.body.toString());
I think I should be getting a JSON data response which I'm getting properly with postman but in flutter I'm getting empty response.
Things I tried:
encoding the body with jsonencode
correct syntax formatting
writing the body in plain json string
var headers = {
'Api-Key': 'yCTZwGASncUthpMkMkbQDjcUdrrM2r8v',
'Content-Type': 'application/json'
};
var request = http.MultipartRequest('POST', Uri.parse('https://api.opensubtitles.com/api/v1/download'));
request.fields.addAll({
'file_id': '123'
});
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
}
else {
print(response.reasonPhrase);
}

Invalid argument(s): No host specified in URI

auth_service.dart
The following ArgumentError was thrown resolving an I/flutter (11774): Invalid argument(s): No host specified in URI
This my Code pleaseeeeeeeee help meeee
class AuthService {
String baseUrl = 'http://shamo-backend.buildwithangga.id/api';
Future<UserModel?> register({
required String name,
required String username,
required String email,
required String password,
}) async {
// ignore: unused_local_variable
var url = '$baseUrl/register';
var header = {'Content-Type': 'application/json'};
var body = jsonEncode({
'name': name,
'username': username,
'email': email,
'password': password,
});
var response = await http.post(
Uri(),
headers: header,
body: body,
);
print(response.body);
if (response.statusCode == 200) {
var data = jsonDecode(response.body)['data'];
UserModel user = UserModel.fromJson(data['user']);
// ignore: prefer_interpolation_to_compose_strings
user.token = 'Bearer ' + data['access_token'];
return user;
} else {
throw Exception('Gagal Register');
}
}
}
Iwant save like this enter image description here
Please Helpme
You are not passing any url in http.post. Replace
var response = await http.post(
Uri(),
headers: header,
body: body,
);
With
var response = await http.post(
Uri.parse(url),
headers: header,
body: body,
);
Refer this documentation for detail information
Use it like this to resove this issue
// edit this line of your code
====> var header = {'Content-Type': 'application/json'};
// with this
====> var header = {'Content-Type': 'application/json; charset=UTF-8'};
// FULL CODE
class CreateGoalModals {
Future<Add_Goal_Status> create_goal_WB(
String name,
String username,
String email,
String password,
) async {
final response = await http.post(
Uri.parse(
your_application_base_url,
),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(
<String, String>{
'name': name,
'username': username,
'email': email,
'password': password,
},
),
);
if (response.statusCode == 201) {
print('=========> 201');
print(response.body);
} else if (response.statusCode == 200) {
print('==========> 200');
print(response.body);
// after SUCCESS
if (success_text == "success") {
print('=========> SUCCESSFULLY <===========');
} else {
print('========> SUCCESS WORD FROM SERVER IS WRONG <=========');
}
// throw Exception('SOMETHING WENT WRONG. PLEASE CHECK');
} else {
print("============> ERROR");
print(response.body);
}
}
}

how to send token while post request

have a great day, i have a silly problem, don't mind as i am noob. ok my problem is, i have a token which i received after i login, now i have to post a data but for that i have to include this token in my header, but i don't know how to....
here is my token, which i received after login as response
{
"token": "8d18265645a87d608868a127f373558ac2e131a6"
}
Here, i have to implement in flutter
apiData.ApiData app = apiData.ApiData();
final String apiURl = app.api;
SharedPreferences pref = await SharedPreferences.getInstance();
String? email = pref.getString("useremail");
String? token = pref.getString('token');
String date = DateFormat("yyyy-MM-dd").format(DateTime.now());
String time = DateFormat("Hms").format(DateTime.now());
print(time);
print(date);
dynamic response =
await http.post(Uri.parse(apiURl + "/api/user-log/"), body: {
'user': email,
'start_time': time,
'start_date': date,
});`
Here in the documentation you can found the following snippet, where the headers are sent with the HTTP request:
Future<http.Response> createAlbum(String title) {
return http.post(
Uri.parse('https://jsonplaceholder.typicode.com/albums'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'title': title,
}),
);
}
Add header in the post method as below:
var headers = {
'authorization': token,
"Accept": "application/json"
};
dynamic response =
await http.post(Uri.parse(apiURl + "/api/user-log/"),headers: headers), body: {
...
});
final response = await http.get(
Uri.parse(apiURl + "/api/user-log/"),
body: {}
headers: {
HttpHeaders.authorizationHeader: "<Your token here>",
},
);
Documentation here

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.

how to get the values inside Instance of 'Future<Response<dynamic>?>' in Flutter?

I'm using Dio for http requests and the function for post method is like this :
Future<Response?> post(String url, dynamic data) async {
try {
Response response = await baseAPI.post(url, data: data);
return response;
} on DioError catch(e) {
throw Failure(e.message);
}
}
then when I use this post method the response I get is in Instance of 'Future<Response?>'. So how can I access the response data inside this?
void login(String email, String password) {
dynamic data = jsonEncode(<String, String>{
'email': email,
'password':password,
});
Future<Response?> response = loginService.post('https://reqres.in/api/login',data) ;
print(response);
print('response data print');
}
as your loginService.post is returning a future type, you can get the Response value by adding await in front of it, but then your login function will have be declare it as async, such as:
Future<void> login(String email, String password) async {
dynamic data = jsonEncode(<String, String>{
'email': email,
'password':password,
});
Response? response = await loginService.post('https://reqres.in/api/login',data) ;
print(response);
print('response data print');
}
Or if you do not wish to async your login function, you can add .then to your post loginService.post like below:
Response? response;
loginService.post('https://reqres.in/api/login',data).then((data) => response = data)