How to format body for form-data header - flutter

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!');

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

Flutter http post request gives status code 401

I am using API to verify phone number provided by user.... on postman api give perfect response and give OTP code in response but in flutter status code 401 is returned
here is my code
Future verifyPhone(String phoneNumber) async {
try {
String token = "528724967b62c6c9e546aeaee1b57e234991ad98";
var body = <String, String>{};
body['user_number'] = phoneNumber;
var url = Uri.parse(ApiKeys.phoneVerifyApiKey);
var response = await http.post(
url,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"authentication": "Bearer $token"
},
body: body,
);
if (response.statusCode == 200) {
print("Code sent");
} else {
print("Failed to send code");
print(response.statusCode);
}
} catch (err) {
print(err.toString());
}
notifyListeners();
}
instead of "code sent" i get "failed to send code" and status code 401
EDIT
You can send form request this way
Future verifyPhone(String phoneNumber) async {
try {
String token = "528724967b62c6c9e546aeaee1b57e234991ad98";
var body = <String, String>{};
body['user_number'] = phoneNumber;
var url = Uri.parse(ApiKeys.phoneVerifyApiKey);
var headers ={
"Content-Type": "application/x-www-form-urlencoded",
"authentication": "Bearer $token"
};
var request = http.MultipartRequest('POST', url)
..headers.addAll(headers)
..fields.addAll(body);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print("Code sent");
} else {
print("Failed to send code");
print(response.statusCode);
}
} catch (err) {
print(err.toString());
}
notifyListeners();
}
EDIT
To access :
var _data = jsonDecode(response);
var list = _data["data"];
print(list[0]['otp_code']);

How do i Authorize myself to GET User Api [duplicate]

The post request is throwing an error while setting the header map.
Here is my code
Future<GenericResponse> makePostCall(
GenericRequest genericRequest) {String URL = "$BASE_URL/api/";
Map data = {
"name": "name",
"email": "email",
"mobile": "mobile",
"transportationRequired": false,
"userId": 5,
};
Map userHeader = {"Content-type": "application/json", "Accept": "application/json"};
return _netUtil.post(URL, body: data, headers:userHeader).then((dynamic res) {
print(res);
if (res["code"] != 200) throw new Exception(res["message"][0]);
return GenericResponse.fromJson(res);
});
}
but I'm getting this exception with headers.
══╡ EXCEPTION CAUGHT BY GESTURE ╞═
flutter: The following assertion was thrown while handling a gesture:
flutter: type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, String>'
flutter:
flutter: Either the assertion indicates an error in the framework itself, or we should provide substantially
flutter: more information in this error message to help you determine and fix the underlying cause.
flutter: In either case, please report this assertion by filing a bug on GitHub:
flutter: https://github.com/flutter/flutter/issues/new?template=BUG.md
flutter:
flutter: When the exception was thrown, this was the stack:
flutter: #0 NetworkUtil.post1 (package:saranam/network/network_util.dart:50:41)
flutter: #1 RestDatasource.bookPandit (package:saranam/network/rest_data_source.dart:204:21)
Anybody facing this issue? I didn't find any clue with the above log.
Try
Map<String, String> requestHeaders = {
'Content-type': 'application/json',
'Accept': 'application/json',
'Authorization': '<Your token>'
};
You can try this:
Map<String, String> get headers => {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": "Bearer $_token",
};
and then along with your http request for header just pass header as header
example:
Future<AvatarResponse> getAvatar() async {
var url = "$urlPrefix/api/v1/a/me/avatar";
print("fetching $url");
var response = await http.get(url, headers: headers);
if (response.statusCode != 200) {
throw Exception(
"Request to $url failed with status ${response.statusCode}: ${response.body}");
}
var avatar = AvatarResponse()
..mergeFromProto3Json(json.decode(response.body),
ignoreUnknownFields: true);
print(avatar);
return avatar;
}
I have done it this way passing a private key within the headers. This will also answer #Jaward:
class URLS {
static const String BASE_URL = 'https://location.to.your/api';
static const String USERNAME = 'myusername';
static const String PASSWORD = 'mypassword';
}
In the same .dart file:
class ApiService {
Future<UserInfo> getUserInfo() async {
var headers = {
'pk': 'here_a_private_key',
'authorization': 'Basic ' +
base64Encode(utf8.encode('${URLS.USERNAME}:${URLS.PASSWORD}')),
"Accept": "application/json"
};
final response = await http.get('${URLS.BASE_URL}/UserInfo/v1/GetUserInfo',
headers: headers);
if (response.statusCode == 200) {
final jsonResponse = json.decode(response.body);
return new UserInfo.fromJson(jsonResponse);
} else {
throw Exception('Failed to load data!');
}
}
}
Try this
Future<String> createPost(String url, Map newPost) async {
String collection;
try{
Map<String, String> headers = {"Content-type": "application/json"};
Response response =
await post(url, headers: headers, body: json.encode(newPost));
String responsebody = response.body;
final int statusCode = response.statusCode;
if (statusCode == 200 || statusCode == 201) {
final jsonResponse = json.decode(responsebody);
collection = jsonResponse["token"];
}
return collection;
}
catch(e){
print("catch");
}
}
Future<String> loginApi(String url) async {
Map<String, String> header = new Map();
header["content-type"] = "application/x-www-form-urlencoded";
header["token"] = "token from device";
try {
final response = await http.post("$url",body:{
"email":"test#test.com",
"password":"3efeyrett"
},headers: header);
Map<String,dynamic> output = jsonDecode(response.body);
if (output["status"] == 200) {
return "success";
}else{
return "error";
} catch (e) {
print("catch--------$e");
return "error";
}
return "";
}
void getApi() async {
SharedPreferences prefsss = await SharedPreferences.getInstance();
String tokennn = prefsss.get("k_token");
String url = 'http://yourhost.com/services/Default/Places/List';
Map<String, String> mainheader = {
"Content-type": "application/json",
"Cookie": tokennn
};
String requestBody =
'{"Take":100,"IncludeColumns":["Id","Name","Address","PhoneNumber","WebSite","Username","ImagePath","ServiceName","ZoneID","GalleryImages","Distance","ServiceTypeID"],"EqualityFilter":{"ServiceID":${_radioValue2 != null ? _radioValue2 : '""'},"ZoneID":"","Latitude":"${fav_lat != null ? fav_lat : 0.0}","Longitude":"${fav_long != null ? fav_long : 0.0}","SearchDistance":"${distanceZone}"},"ContainsText":"${_txtSearch}"}';
Response response = await post(url , headers: mainheader ,body:requestBody);
String parsedata = response.body;
var data = jsonDecode(parsedata);
var getval = data['Entities'] as List;
setState(() {
list = getval.map<Entities>((json) => Entities.fromJson(json)).toList();
});
}

Http Post in Flutter not Sending Headers

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

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