How to set list<String> in body http.post - flutter

in postman body:
id:2
images[]:image1 base64
image[]:image2 base64
how to set body to send request?
this my code
var uri = 'url';
var images = List<String>();
Map data = {
'id': id,
'images[]' : images,
};
var body = json.encode(data);
final response = await http.post(uri, body: body);
print("${response.statusCode}");
print("${response.body}");
if (response.statusCode == 200) {
return Model.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to load post');
}
response is failed
what's wrong with my code?

Related

Http Request Flutter didn't have body

I have a project with Flutter. And I want to get data from API. In my other project, I don't have any problem. But in this project, I have a problem. When I debug the process, in HTTP response didn't have body from API.
In class AuthService to get the API.
Future<ResponseCheckNIP> checkNIP({String? nip}) async {
var url = '$baseUrl/check-nip-new/$nip';
var header = {
'Content-Type': 'application/json',
};
// var body = jsonEncode({'nip': nip});
var response = await http.get(Uri.parse(url), headers: header);
if (response.statusCode == 200) {
var data = jsonDecode(response.body);
ResponseCheckNIP responseCheckNIP = ResponseCheckNIP.fromJson(data);
return responseCheckNIP;
} else {
throw Exception('Get NIP Failed');
}
}
And when I debug it, I get this
as we see, there is no body in there. Am I did something wrong?
If you look closely, the data is actually in the response.bodyBytes.
And Since you cannot directly convert bytes to json with dart, convert bytes to String first then decode the String using jsonDecode.
Below is the modified code.
Future<ResponseCheckNIP> checkNIP({String? nip}) async {
var url = '$baseUrl/check-nip-new/$nip';
var header = {
'Content-Type': 'application/json',
};
var response = await http.get(Uri.parse(url), headers: header);
if (response.statusCode == 200) {
// Get body bytes from response
final bytes = response.bodyBytes;
// Convert bytes to String then decode
final data = jsonDecode(utf8.decode(bytes));
ResponseCheckNIP responseCheckNIP = ResponseCheckNIP.fromJson(data);
return responseCheckNIP;
} else {
throw Exception('Get NIP Failed');
}
}
Hope this helps.
Thank you.

Flutter upload image

Get Api Flutter dont working
I tried various methods, if the link is wrong, then it should at least be displayed json text in terminal
photo should be shown
Future<dynamic> getPhotoUrl(int profileID) async {
print("get Photo url $profileID");
var client = http.Client();
var url = Uri.parse("$profileBaseUrl/api/v2/profiles/$profileID/photos");
Map<String, String> headers = {
'APIVersion': '1',
"Authorization": token,
};
var response = await client.get(url, headers: headers);
if (200 == response.statusCode) {
return response.body;
} else {
}
print("avatar url: $currentPhotoUrl");
}
tried this and it doesn't work
Future<void> getPhotoUrl(int profileID) async {
print("get photo url $profileID");
var client = http.Client();
Map<String, String> headers = {
"Authorization": token
};
final http.Response response = await client.get(
Uri.parse("$profileBaseUrl/api/v2/profiles/$profileID/photos"),
headers: headers);
if (response.statusCode == 200) {
Map responseBody = jsonDecode(response.body);
var data = responseBody["data"];
if (data.length < 1) {}
else {
currentPhotoUrl.value = data[0]["content"][0]["medium"];
}
} else {
throw WebSocketException("server error: ${response.statusCode}");
}
print("photos url: $currentPhotoUrl");
}

Convert data from API server to protobuf error with Dart & Flutter

Future<dynamic> fetchNews(String lid, String realsize) async {
String url = "http://192.168.55.101:8000/todo";
final response =
await http.get(Uri.parse(url),
headers: <String, String>{
// "Content_Type" : "application/x-protobuf"
},
);
if (response.statusCode == 200) {
whatNewsMsg data = whatNewsMsg.fromJson(json.decode(response.body.toString()));
print("data: " + data.title); // ====> Here I get error
return response.body.toString();
} else {
throw Exception('Unable to fetch news from the REST API');
}
}
var data = whatNewsMsg.create()..mergeFromProto3Json(jsonDecode(response.body));

How to upload image to server API with Flutter [duplicate]

This question already has an answer here:
Upload image with http.post and registration form in Flutter?
(1 answer)
Closed 3 years ago.
I am new to Flutter development. My problem is that I try to upload the image but I keep getting failed request.
This piece of code is where I connect it with a server API which will receive the image file from Flutter. String attachment which consist of the image path that is passed from createIncident function located at another page.
Future<IncidentCreateResponse> createIncident( String requesterName, String requesterEmail,
String requesterMobile, String attachment, String title,
String tags, String body, String teamId,
String address ) async {
IncidentCreateResponse incidentCreateResponse;
var url = GlobalConfig.API_BASE_HANDESK + GlobalConfig.API_INCIDENT_CREATE_TICKETS;
var token = Auth().loginSession.accessToken;
var postBody = new Map<String, dynamic>();
postBody["requester_name"] = requesterName;
postBody["requester_email"] = requesterEmail;
postBody["requester_mobile_no"] = requesterMobile;
postBody["attachment"] = attachment;
postBody["title"] = title;
postBody["tags"] = tags;
postBody["body"] = body;
postBody["teamId"] = teamId;
postBody["address"] = address;
// Await the http get response, then decode the json-formatted responce.
var response = await http.post(
url,
body: postBody,
headers: {
'X-APP-ID': GlobalConfig.APP_ID,
"Accept": "application/json; charset=UTF-8",
// "Content-Type": "application/x-www-form-urlencoded",
HttpHeaders.authorizationHeader: 'Bearer $token',
'token': GlobalConfig.API_INCIDENT_REPORT_TOKEN
}
);
if ((response.statusCode == 200) || (response.statusCode == 201)) {
print(response.body);
var data = json.decode(response.body);
incidentCreateResponse = IncidentCreateResponse.fromJson(data['data']);
} else {
print("createIncident failed with status: ${response.statusCode}.");
incidentCreateResponse = null;
}
return incidentCreateResponse;
}
This is the code snippet where I get the image path from the selected image from the gallery
Future getImageFromGallery(BuildContext context) async {
var picture = await ImagePicker.pickImage(source: ImageSource.gallery);
setState((){
_imageFile = picture;
attachment = basename(_imageFile.path);
});
Navigator.of(context).pop();
}
This is the code where I passed the attachment string to the HTTP Response
this.incidentService.createIncident(
Auth().loginSession.name,
Auth().loginSession.email,
Auth().loginSession.mobile_no,
this.attachment,
this._titleController.text,
this._tags,
this._contentController.text,
this._teamId,
this._addressController.text
).then((IncidentCreateResponse res) {
if (res != null) {
print('Ticket Id: ' + res.id);
// Navigator.pop(context);
this._successSubmittionDialog(context);
} else {
this._errorSubmittionDialog(context);
}
}
You can upload image using multipart or base64 Encode.
For uploading image using multipart Visit the Official documentation
For uploading image using base64 Encode you can checkout the Tutorial Here
I suggest using multipart image upload as it is even reliable when your image or files are larger in size.
Hope this could help you,
create a function to upload your image after picking or clicking an image like,
Future<ResponseModel> uploadPhoto(
String _token,
File _image,
String _path,
) async {
Dio dio = new Dio();
FormData _formdata = new FormData();
_formdata.add("photo", new UploadFileInfo(_image, _path));
final response = await dio.post(
baseUrl + '/image/upload',
data: _formdata,
options: Options(
method: 'POST',
headers: {
authTokenHeader: _token,
},
responseType: ResponseType.json,
),
);
if (response.statusCode == 200 || response.statusCode == 500) {
return ResponseModel.fromJson(json.decode(response.toString()));
} else {
throw Exception('Failed to upload!');
}
}
then you can use use uploadImage,
uploadImage(_token, _image,_image.uri.toFilePath()).then((ResponseModel response) {
//do something with the response
});
I have used Dio for the task, you can find more detail about dio here
Add this to your package's pubspec.yaml file:
dependencies:
dio: ^3.0.5
Then import it in your Dart code, you can use:
import 'package:dio/dio.dart';
To upload image using multipart API use this code ie
Add this library dio in your project in pubspec.yaml file
dio: ^3.0.5
and import this in your class
import 'package:dio/dio.dart';
Declare this variable in your class like State<CustomClass>
static var uri = "BASE_URL_HERE";
static BaseOptions options = BaseOptions(
baseUrl: uri,
responseType: ResponseType.plain,
connectTimeout: 30000,
receiveTimeout: 30000,
validateStatus: (code) {
if (code >= 200) {
return true;
}
});
static Dio dio = Dio(options);
then use this method to upload file
Future<dynamic> _uploadFile() async {
try {
Options options = Options(
//contentType: ContentType.parse('application/json'), // only for json type api
);
var directory = await getExternalStorageDirectory(); // directory path
final path = await directory.path; // path of the directory
Response response = await dio.post('/update_profile',
data: FormData.from({
"param_key": "value",
"param2_key": "value",
"param3_key": "value",
"profile_pic_param_key": UploadFileInfo(File("$path/pic.jpg"), "pic.jpg"),
}),
options: options);
setState(() {
isLoading = false;
});
if (response.statusCode == 200 || response.statusCode == 201) {
var responseJson = json.decode(response.data);
return responseJson;
} else if (response.statusCode == 401) {
print(' response code 401');
throw Exception("Incorrect Email/Password");
} else
throw Exception('Authentication Error');
} on DioError catch (exception) {
if (exception == null ||
exception.toString().contains('SocketException')) {
throw Exception("Network Error");
} else if (exception.type == DioErrorType.RECEIVE_TIMEOUT ||
exception.type == DioErrorType.CONNECT_TIMEOUT) {
throw Exception(
"Could'nt connect, please ensure you have a stable network.");
} else {
return null;
}
}
}

How do I upload image in Flutter App to my server and decode the json response from the server?

I have an Endpoint on my server which accepts multipart/form-data and sends back json as a response.
I want to send an Image from my flutter App to my server and Decode the json received from the server.
You can use http.MultipartRequest for that
Example:-
static Future<UploadImageRes> uploadImage(int id, File imageFile) async {
if (imageFile != null) {
var stream = new http.ByteStream(imageFile.openRead());
var length = await imageFile.length();
String token = PreferenceUtils.getString(AppConstants.LOGGED_IN);
var uri = Uri.parse(UrlConstants.ADD_RECIPE_PHOTO);
LogUtils.d("====uri : $uri");
LogUtils.d("====recipeId : $id");
var request = new http.MultipartRequest("POST", uri);
String fileName = imageFile.path.split("/").last;
var multipartFile = new http.MultipartFile('photo', stream, length,
filename: fileName, contentType: new MediaType('image', 'jpeg'));
request.headers.addAll({"Authorization": "Bearer $token"});
request.files.add(multipartFile);
request.fields["recipeId"] = "$id";
var response = await request.send();
var statusCode = response.statusCode;
LogUtils.d("====statusCode : $statusCode");
if (statusCode < 200 || statusCode >= 400) {
throw new ApiException("Uploading failed");
}
final respStr = await response.stream.bytesToString();
return Future.value(UploadImageRes.fromJson(JsonDecoder().convert(respStr)));
} else {
throw new ApiException("Uploading failed");
}
}
In final respStr = await response.stream.bytesToString(); you will get your api response