How to post a map of string and list with flutter - flutter

I am trying to send a Map of string and list which is like:
Map<String, List<int>> results = {
"tags": [5 , 10]
}
Object headers = {
HttpHeaders.authorizationHeader: "Bearer ${accessToken}",
"Accept": "application/json",
};
and I post that like this:
post() {
return http
.post("$resource/$baseName/$id$query",
headers: headers,
body: results ,
)
.then((http.Response response) {
return json.decode(response.body);
}).catchError((err) {
print(err);
});
}
and I got this error:
type 'List<int>' is not a subtype of type 'String' in type cast
also I guess that I should send
Map<String,String>
but I have
Map<String, List<int>>
I try many things but am also new to flutter so I got confusing a lot
Thanks if someone can help me .
EDIT:
i try with dio
try {
Response response =
await Dio().post("$resource/$baseName/$id$query", data: {
'tags': [1, 2]
},
options: Options(headers: headers)
);
print(response);
} catch (e) {
print(e);
}

Are you encoding your data when you send it? Try encoding your data before sending it. You specify your header to accept application/json, but you might not be sending json.
See: https://api.dartlang.org/stable/2.5.0/dart-convert/jsonEncode.html
import 'dart:convert';
Map<String, List<int>> results = {
"tags": [5 , 10]
};
final encodedResults = jsonEncode(results); // send these encoded results.

How do you create this map?
Wouldn't it be possible to start a .toString in the list?
Note: I suggest using the Dio plugin, it makes it much easier to work with requests in webServices, in my opinion of course!
Take a look here: https://pub.dev/packages/dio
Map<String, List<int>> results = {
"tags": [5 , 10]
}
var dio = Dio();
FormData data = FormData();
final local = '$baseName/$id$query'
dio.options.baseUrl = source;
data.add('tags', results.toString);
try{
final response = await dio.post(local, data: data, options: Options(
method: 'POST',
responseType: ResponseType.json
));
final body = jsonDecode(response.data);
print(body);
}catch(e){
print(e);
return e;
}

Related

how to use flutter dio connect-type multipart?

my code here
Dio dio = new Dio();
String fileName = event.file!.path.split('/').last;
FormData formData = FormData.fromMap({
"file":
await MultipartFile.fromFile(event.file!.path, filename: fileName),
});
try {
var response = await dio.post(
"url",
data: formData,
options: new Options(
contentType: "multipart/form-data",
headers: {
"token": await getToken(),
// "Content-Type": "multipart/form-data"
}),
// headers: {"token": "test:1234"}),
);
}
catch (e){
print(e);
}
my error version 1
error type. DioErrorType.other
error : SocketException : OS Error Connection refused,errorno=61
and
my error version 2
error type. DioErrorType.response
error : Http status error[400]
my requestOptions here
method = "POST"
_defaultContentType = "multipart/form-data"
How can I hand over the file to the server? The problem I think is that the content-type is not suitable, so there seems to be an error.
I have a similar implementation. I also use Dio, though in my code, I have it abstracted away with _api.
Future<Response> uploadLogo({#required File file}) async {
String fileName = file.path.split('/').last;
FormData formData = FormData.fromMap({"file": await MultipartFile.fromFile(file.path, filename:fileName) });
return await _api.post(url: url, data: formData);
}
Note that I don't even set the content type. I suspect that Dio looks at the type of object in the data parameter, and handles the appropriate headers/encoding under the hood.
Also, if you have having the content-type set to something unexpected, I'd recommend checking if you are using any RequestInterceptor's. I was, and had to write an exception, because I was setting it correctectly, by my RequestInterceptor was overriding it, (because all of my other endpoints wanted JSON):
class RequestInterceptor extends InterceptorsWrapper {
#override
void onRequest(RequestOptions options, handler) {
if(!options.headers.containsKey('content-type')) {
options.headers['content-type'] = 'application/json';
}
// ...
super.onRequest(options, handler);
}
}

how to send an object in formdata flutter

I am currently working on a mobile app and I am stuck in this for days now. I have been trying to send a post request to create an object "Leave" as represents the code below. The request body is formData with a key 'leave' and value 'jsonObject'.I've tried a lot of methods and it has a relation with 'Content-type'I suppose. If i change it to 'multipart/form-data' the response becomes 500 and if it is 'application/json' i always get 415 unsupported mediaType. This is my code using dio package, any advice would be helpful guys, thank u on advance.Postman request works fine
Future createLeave() async {
var leave = Conge(
dateDemand: DateTime.now(),
dateEnd: DateTime.now().add(Duration(days: 3)),
dateStart: DateTime.now().add(Duration(days: 1)),
type: "CSS",
endDateDaySlot: "X",
startDateDaySlot: "X",
);
Map<String, String> heads = {
"X-Auth-Token": UserPreferences().token,
"Content-type": 'application/json',
"accept": "application/json"
};
FormData formData = FormData.fromMap({"leave": leave.toJson()});
var dio = Dio();
try {
Response response = await dio.post(API + '/leave/add',
data: formData,
options:
Options(headers: heads, contentType: Headers.jsonContentType));
} on Exception catch (e) {
print(e);
}
}
I have also tried to use MultiPartRequest but i always get 400 as a response, the request sent by the client was syntactically incorrect here is my code could anyone help me with this please
Future create(Conge leave) async {
String url = API + "/leave/add";
var uri = Uri.parse(url);
var request = new http.MultipartRequest("POST", uri);
Map<String, String> heads = {
"X-Auth-Token": UserPreferences().token,
"Content-type": 'application/json',
};
request.headers.addAll(heads);
request.fields['leave'] = json.encode(leave.toJson());
var response = await request.send();
print(response.statusCode);
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
}
Please try to disable the firewall of windows, if it works then make an exception for it in the firewall.

Incomplete response JSON body with flutter http.Request.send()

I am not sure what is going on with my function. I am trying to have a generic request function that I can use with any request method (GET, POST, etc...). Everything is working well, except for the POST response, it is missing data. I double checked what is expected to be returned and compared it with the response from Postman and my code. My code produces less data than expected and Postman.
Here is what I am doing
class HttpClientHandler {
String baseUrl = 'jsonplaceholder.typicode.com';
String path = '/posts';
static const Map<String, String> defaultHeaders = {'': ''};
static const Map<String, String> defaultBody = {'': ''};
Future<dynamic> request(HttpMethod method,
{Map<String, String> headers = defaultHeaders,
Map<String, dynamic> body}) async {
var uri = Uri.https(baseUrl, '$path');
var request = http.Request(method.type, uri);
request.headers.addAll(headers);
request.body = body.toString();
var response = await request.send();
if (response.statusCode >= 200 && response.statusCode <= 299) {
String rawData = await response.stream.transform(utf8.decoder).join();
return jsonDecode(rawData);
} else {
throw Exception();
}
}
}
The caller simply does the following:
var _client = HttpClientHandler();
var data = await _client.request(HttpMethod.POST, body: {'title': 'foo', 'body': 'bar', 'userId': 1});
print(data);
The response I get is:
{id: 101}
The expected response is:
{
"title": "foo",
"body": "bar",
"userId": "1",
"id": 101
}
I am using import 'package:http/http.dart' as http; package. Is this a stream, transform, or headers issue?
I found what was wrong in my implementation, I didn't jsonEncode my request body. The test API I am using here replies the same request body it receives. Since I wasn't encoding the body correctly, it only was recognizing the first data being sent.
So, the fix is to change this line:
request.body = body.toString();
to this line:
request.body = jsonEncode(body);
Also, I ended up parsing the stream byte to string differently, from:
String rawData = await response.stream.transform(utf8.decoder).join();
To:
String rawData = await response.stream.bytesToString();

Can't able to call simple API

I just want to call simple API but can't able to call. If I tried to call in Postman then get proper response.
Look at my code
Future<AppServiceModel> getAllItems({String pageID = ""}) async {
final String _url = "http://www.textsite.com/api/app-view?page_id=";
final finalURL = Uri.encodeFull(_url);
try {
return http.get(finalURL, headers: {
HttpHeaders.contentTypeHeader: 'application/x-www-form-urlencoded',
HttpHeaders.acceptHeader: "application/json",
HttpHeaders.authorizationHeader: 'Bearer $accessToken'
}).then((response) {
Map<String, dynamic> _resDic =
Map<String, dynamic>.from(json.decode(response.body));
print('===>> Response : $_resDic');
return AppServiceModel.fromJson(_resDic);
});
} catch (e) {
print("Error: $e");
return null;
}
}
I also tried to pass QueryParameters by following How do you add query parameters to a Dart http request?
But each time get response
Response : {code: 7, msg: Your login session has expired. Please login again to continue., data: []}
I'm damm sure, passing right TOKEN.
Below is output of Postman

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