Flutter request Filemaker API (FieldData) - flutter

Im trying to access one specific call to the filemaker API, I have several requests which are working..
but if i try to do one with the fieldData field it doesn't work
var body = {"fieldData": {
"testId": myId
}};
HttpClient httpClient = new HttpClient();
HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));
request.headers.set('content-type', 'application/json');
request.headers.add('authorization', 'bearer $token');
request.add(utf8.encode(json.encode(body)));
HttpClientResponse httpClientResponse = await request.close();
String reply = await httpClientResponse.transform(utf8.decoder).join();
httpClient.close();
I just get the error:
{"messages":[{"message":"Unknown parameter(s): fieldData","code":"960"}],"response":{}}
Edit:
Url: https://{Server}/fmi/data/vLatest/databases/{database}/layouts/DataAPIaddresses/records/{id}

Found it:
HttpClientRequest request = await httpClient.patchUrl(Uri.parse(url));
You have to patchUrl, because Filemaker wants a Patch request...

Related

Content-Type header is text/html when uploading a file to the server using a multipart request only in iOS

I'm sending a multipart request to a server in order to upload a file, however this is working only on Android, when it comes to iOS I get an Internal Server Error with a status code 500. When I print the headers on Android the content type is application json, but on iOS the content type is text/html. Is this a server-side problem? or should I set any other header in the multipart request besides authorization header?
This is the code of the request
Future<Map<String, dynamic>> uploadFileToEvent(File file, int eventId) async {
var stream = http.ByteStream(file.openRead());
stream.cast();
var length = await file.length();
String url = '$_url/event/$eventId/media/';
final _header = <String, String>{
'Authorization': 'Bearer ' + _prefs.token,
};
var uri = Uri.parse(url);
var request = http.MultipartRequest("POST", uri);
var multipartFileSign = http.MultipartFile('file', stream, length, filename: basename(file.path));
request.files.add(multipartFileSign);
request.headers.addAll(_header);
var response = await request.send();
final resp = await http.Response.fromStream(response);
}

Flutter http request returns error code 502, but same request in python returns http code 200

When I debug this function I get the http error code 502:
Future<bool> checkSessionID(String sessionId) async {
Uri uri = Uri.parse("https://myurl.com");
var myobj = {
"session": sessionId,
};
HttpClient client = HttpClient(context: SecurityContext()..setTrustedCertificatesBytes(creds.key.codeUnits));
var request = await client.postUrl(uri);
request.headers.set('content-type', 'application/json');
request.add(utf8.encode(jsonEncode(myobj)));
var response = await request.close();
// encode response to json
var json = jsonDecode(await response.transform(utf8.decoder).join());
return json["status"];
}
but when I remove the JSON payload it returns code 200:
Future<bool> checkSessionID(String sessionId) async {
Uri uri = Uri.parse("https://myurl.com");
var myobj = {
"session": sessionId,
};
HttpClient client = HttpClient(context: SecurityContext()..setTrustedCertificatesBytes(creds.key.codeUnits));
var request = await client.postUrl(uri);
//request.headers.set('content-type', 'application/json');
//request.add(utf8.encode(jsonEncode(myobj)));
var response = await request.close();
// encode response to json
var json = jsonDecode(await response.transform(utf8.decoder).join());
return json["status"];
}
when I run this python code it works just fine:
url = 'https://myurl.com'
payload = {"session": session_id}
request = requests.post(url, json = payload, verify="cert.cer")
Am I encoding the json wrong in the dart code or what is my mistake?

Flutter dio image upload not working throws server 401 error, but works in postman

This is my postman request with a header Authorization Bearer Token.
I am trying to upload the image, everything is set up as mentioned with the documents dio and exactly the same as the postman parameter, but it is throwing a 401 error, it is giving me an Unauthorized error, it would appear that it is not taking the token to process and upload the file. I was reading and moving options that were mentioned in post, but unfortunately I have not been successful.
I would be very grateful if someone could give me some guidance and help me to get the process done.
My dio request:
employeeAttachFile(File file) async {
final SecureStorage _secureStorage = SecureStorage();
final token = await _secureStorage.readToken('token');
final String uri = '${ApiPaths.basisApi}${ApiPaths.addEmployeesFile}15';
String fileName = file.path.split('/').last;
print(fileName);
FormData data = FormData.fromMap({
"file": await MultipartFile.fromFile(
file.path,
filename: fileName,
),
});
Dio dio = new Dio(BaseOptions(
headers: {"Authorization": token}, contentType: "application/json"));
await dio.post(uri, data: data).then((response) {
var jsonResponse = jsonDecode(response.toString());
print(jsonResponse);
}).catchError((error) => print(error));
}
This is my error:
Try
{'Authorization': 'Bearer $token'}

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.

body not sending using map in flutter

HttpClient client = new HttpClient();
client.badCertificateCallback = ((X509Certificate cert, String host, int port) => true);
String url ='https://dev.jobma.com:8090/v4/jobseeker/login';
Map map = {
"email":"hope#yopmail.com",
"password":"123456"
};
print(map);
HttpClientRequest request = await client.postUrl(Uri.parse(url));
request.headers.set('content-type', 'application/json');
request.add(utf8.encode(json.encode(map)));
HttpClientResponse response = await request.close();
String reply = await response.transform(utf8.decoder).join();
print(reply);
and response from server showing this
{"error": 1, "data": {}, "message": "Please add mandatory fields: email, password"}
It is much easier if you can use http package available in dart pub.
import 'package:http/http.dart' as http;
String url = 'https://dev.jobma.com:8090/v4/jobseeker/login';
Map map = {
"email": "hope#yopmail.com",
"password": "123456"
};
var response = await http.post(url, body: map);
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
It seems that without the "content-length" headers, that server isn't accepting the request properly. This will make your code work:
HttpClient client = new HttpClient();
client.badCertificateCallback =
((X509Certificate cert, String host, int port) => true);
String url = 'https://dev.jobma.com:8090/v4/jobseeker/login';
Map map = {
"email": "hope#yopmail.com",
"password": "123456"
};
print(map);
// Creating body here
List<int> body = utf8.encode(json.encode(map));
HttpClientRequest request = await client.postUrl(Uri.parse(url));
request.headers.set('content-type', 'application/json');
// Setting the content-length header here
request.headers.set('Content-Length', body.length.toString());
// Adding the body to the request
request.add(body);
HttpClientResponse response = await request.close();
String reply = await response.transform(utf8.decoder).join();
print(reply);