Http Post in Flutter not Sending Headers - flutter

I am trying to do a post request in Flutter
Below is the code
final String url = Urls.HOME_URL;
String p = 'Bearer $vAuthToken';
final Map<String, String> tokenData = {
"Content-Type": "application/x-www-form-urlencoded",
'Vauthtoken': p
};
final Map<String, String> data = {
'classId': '4',
'studentId': '5'
};
final response = await http.post(Uri.parse(url),
headers: tokenData,
body: jsonEncode(data),
encoding: Encoding.getByName("utf-8"));
if (response.statusCode == 200) {
print(response.body);
} else {
print(response.body);
}
However the header data is not working. I have the correct data and everything. This request works perfectly when done in Postman Client.
Any one has any idea what is wrong?
Any suggestion is appreciated.
Thanks

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);
}

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.

POST call works on Postman but not on Flutter

Future<String> loginUser(User user) async {
var body = jsonEncode({
'strlogin': user.email,
});
Response response = await post(SeguriSignAPIURL.loginUser,
headers: headers,
body: body);
if (response.statusCode == 200) {
var decode = jsonDecode(response.body);
return decode['token'];
} else {
print(response.reasonPhrase);
return '';
}
Hey! When I make this Post call on Postman I get a result, however when I run this code on flutter I get a 400 error. My headers:
final headers = {
'Content-Type': 'application/json; charset=UTF-8',
"Accept": "application/json",
};
Postman:
In Postman you do the request using form-data, but in your Flutter code, you pass json-encoded body.
You either need to use form-data in Flutter or update your server code to accept json content type.

How to format body for form-data header

This might be probably already answered question but I can not find one. How do we format data body for form-data http response? I tried to encode it to json but that didn't work with error
Unhandled Exception: Multipart: Boundary not found
Future<void> createProfile() async {
final body = {
"firstName": "first",
"lastName": "last",
"image": "path-to-image"
};
try {
final http.Response response = await http.post(APIPath.createProfile(),
headers: {"Authorization": "Bearer $token","Content-Type": "multipart/form-data"},
body: json.encode(body)); //<-- this doesn't work
final jsonResponse = json.decode(response.body);
if (response.statusCode != 201) {
throw HttpException(jsonResponse["error"]);
}
} catch (error) {
throw error;
}
}
Flutter Documentation
var uri = Uri.parse('https://example.com/create');
var request = http.MultipartRequest('POST', uri)
..headers['authorization'] = 'auth header value'
..fields['user'] = 'nweiz#google.com'
..files.add(await http.MultipartFile.fromPath(
'package', 'build/image.png',
contentType: MediaType('image', '*')));
var response = await request.send();
if (response.statusCode == 200) print('Uploaded!');

how can i send file with api post method?

Here is my post method , i can send anything with text format but i need to send a file.
if you can, modify just my code. that is easy for catch problem, thanks
getComp() async {
final Map<String, dynamic> jsondata = {
'employee_id':
'${ScopedModel.of<AppModel>(context, rebuildOnChange: true).employee_id}',
'receiver_id': '${recid.text}',
'subject': '${subject.text}',
'message_body': '${msgbody.text}',
'message_attachment':'${filePath}'
};
var jsonresponse = null;
var response = await http.post(
'example.com/compose',
headers: {
"Accept": "application/json"
},
body: jsondata,
);
if (response.statusCode == 200) {
jsonresponse = json.decode(response.body);
print(jsonresponse);
}else{
print('problem');
}
}
Here is my file path picker
getfile(){
filePath = FilePicker.getFilePath(type: FileType.ANY);
}
if you can, modify this code .
convert it to base64 first and insert it to the database. That's how I did it when we developed an app that pass a file to the database.
i solve my problem with dio, :(
if anyone face then use dio
uploadFile() async {
FormData formData = new FormData.fromMap({
'employee_id':
'546546',
'receiver_id': '${recid.text}',
'subject': '${subject.text}',
'message_body': '${msgbody.text}',
'message_attachment': filePath ==null? 'nothing': await
MultipartFile.fromFile("${filePath}",filename: "$filePath}"),
});
Response response = await Dio().post("example.com", data: formData);
print(response);
}