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.
Related
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);
}
I tried to make post method with Bearer Auth in dio but I got Http status error [500]
this is my code
sendData() async {
pr.show();
if (_value == null) {
Future.delayed(Duration(seconds: 0)).then((value) {
setState(() {
pr.hide();
utils.showAlertDialog(
select_area, "warning", AlertType.warning, _scaffoldKey, true);
});
});
return;
}
// Get info for attendance
var dataKey = getKey;
var dataQuery = getQuery;
var userToken = getToken;
// Add data to map
Map<String, dynamic> body = {
'key': dataKey,
'worker_id': getId,
'q': dataQuery,
'lat': _currentPosition.latitude,
'longt': _currentPosition.longitude,
'area_id': _value,
};
// Sending the data to server
final uri = utils.getRealUrl(getUrl, getPath);
Dio dio = Dio();
Map<String, String> mainheader = {
"Content-type": "application/json",
"Authorization": userToken,
};
FormData formData = FormData.fromMap(body);
final response = await dio.post(uri,
data: formData, options: Options(headers: mainheader));
var data = response.data;
and also see this image , I can see the token in my function , so what can I do to fix it
I tried this code but also same
dio.options.headers['content-Type'] = 'application/json';
dio.options.headers["authorization"] = "Bearer userToken";
Update -----
this is the details of the 500 error
as you see its same error when I make the post without auth in postman so I think the problem its from headers
and here with auth
The 500 error is a server-side error.
You should be able to find the cause of the problem on the server.
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);
}
}
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
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;
}