Flutter - http.MultipartRequest() does not work normally - flutter

I am using http package(http: ^0.13.3) in flutter for sending request to the server.
In postman, I can send request and receive response, but in android emulator I can't receive response normally.
Curious thing is that yesterday I can receive response from server, but now I can't receive response.
when, I can receive response from server, when, I can't receive response from server.
But in postman I can receive response always well.
static Future<ResObj?> post(
String url, Map<String, String> data, String? token) async {
try {
var request = new http.MultipartRequest('POST', Uri.parse(url));
request.headers.addAll({
"Authorization": token ?? "",
"Content-Type": "multipart/form-data"
});
data.forEach((key, value) {
request.fields[key] = value;
});
var streamResponse = await request.send();
print(streamResponse);
final responseString = await streamResponse.stream.bytesToString();
if (streamResponse.statusCode == 200) {
final dynamic jsonMap = json.decode(responseString);
return ResObj(
status: true, code: streamResponse.statusCode, data: jsonMap);
} else {
return ResObj(
status: false, code: streamResponse.statusCode, error: "error");
}
} catch (e) {
print(e);
return ResObj(status: false, error: "unknown");
}
}
And postman setting is
In code, I can't receive print(streamResponse), yesterday's code is same as current.
I didn't change my code today.
In code, post function's parameters(url, data, token) are normal.
In my thought, await request.send() function is not working now, but I can't catch any error.
Server is also same status as yesterday, I swear.
Maybe, Is this because of http package?
Please help me to fix this error.

Related

How to convert multiPartRequest's response into normal http response in flutter?

I have to send api request to upload a file to the server.
the pattern:
repo,
provider
service
i have followed fails because of the response multipartRequest sends
how can i convert the request got into normal get/post request ?
Future mutliPartPostRequest(
{required String method,
required String url,
Map<String, String>? headers,
File? file,
String? document,
Map? data}) async {
Map<String, dynamic> jsonResponse;
try {
var request = http.MultipartRequest(method, Uri.parse(url));
data!.forEach((key, value) {
request.fields[key] = value.toString();
});
request.headers['Authorization'] = headers!['authorization']!;
/// [FILTERING] : the null image if there are no photos in the request it will skip adding the photo in the request
if (file != null) {
var picture = await http.MultipartFile.fromPath("photo", file.path);
request.files.add(picture); //adds the photo to the request
}
// Checking the document if it is empty, if it is empty it will skip to add the document in the request
if (document != null) {
var doc = await http.MultipartFile.fromPath('document', document);
request.files.add(doc); // adds the document to the request
}
///Our case starts from this line, while sending multipart request, the response we get is quite different than the normal json data response.
// response => stores the response got
var response = await request.send().timeout(const Duration(seconds: 10)); //sends the request body to the server
// result => coverts the multipart response got from the server to the normal request
var result = await http.Response.fromStream(response);
jsonResponse = returnResponse(result); /// returns the response according to the status code from [returnResponse] function
} on SocketException {
throw FetchDataException({"detail": "No Internet Connection"});
}
return jsonResponse;
}

http put did not send any response in flutter

Hey I have this app where I can update status, and I use http.put method, but it takes forever to response. I got this error
error
And here is the code for http.put
Future<void> mapEventToState(
Emitter<ReportStatusState> emit, ReportStatusEvent event) async {
emit(ReportStatusLoading());
ReportStatusPut statusPut = event.statusPutBody;
// ReportStatusModel model =
// await apiAuthRepository.updateReportStatus(statusPut, event.id);
ReportStatusModel model = await updateReportStatus({'biaya': '0', 'status': 'SELESAI'}, event.id);
print(model);
if (!model.success) {
emit(ReportStatusFailure(model.message));
}
print(model.code);
emit(ReportStatusSuccess());
}}
Future<ReportStatusModel> updateReportStatus(
Map data, String id) async {
final SharedPreferencesManager sharedPreferencesManager =
locator<SharedPreferencesManager>();
String? token =
sharedPreferencesManager.getString(SharedPreferencesManager.keyAccessToken);
try {
final response = await http.put(
Uri.parse('https://api.komplekku.com/officer/api/report/v1/$id'),
body: json.encode(data),
headers: {'Authorization': 'Bearer $token'});
return ReportStatusModel.fromJson(json.decode(response.body));
} catch (e) {
throw Exception(e);
}
}
There is nothing wrong with the API, I already check using Postman and it worked perfectly fine, Anyone know what went wrong?

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.

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

Stop showing error from HTTP or DIO request

I have a problem when I get an error request from API (when server response 500).
I am using dio or http plugin for flutter plug in.
The problem is that flutter does not show any error.
(DIO: resp.data, HTTP: resp.body)
try this for exception handling
try {
Response response = await dio.get('https://google.com');
print(response.statusCode); // 500
print(response.data); // Contains a Dio Error object
} on DioError catch(e) {
print(e);
}
}
You will retrieve in any case a Response object. According to the DIO Handling Errors documentation, it will return a DioError Object.
// DIO Example
Response response = await dio.get('https://google.com');
print(response.statusCode); // 500
print(response.data); // Contains a Dio Error object
The HTTP package works similarly.
var url = 'https://example.com/whatsit/create';
var response = await http.post(url, body: {'name': 'doodle', 'color': 'blue'});
print(response.statusCode); // 500
print(response.body); // Error message
This means in any case you are not receiving directly an error for Flutter, you have to handle the error yourself. For example, you could throw an error, if the status code is not 200.
if(response.statusCode == 200){
// everything works as expected
} else {
throw Error();
}