How to handle Special json POST with Flutter - arrays

I have a JSON POST that I'm sending from my Flutter app as soon in the below code:
// class connecting value from the textfield to database with json
class LoginProfile {
int id;
String CardNumber;
String ExpiryDate;
String ExpiryYear;
String VerifyCode;
LoginProfile({this.id = 0,this.CardNumber
,this.ExpiryDate,this.ExpiryYear});
factory LoginProfile.fromJson(Map<String, dynamic> map) {
return LoginProfile(
id: map["id"],
CardNumber: map["CardNumber"],ExpiryDate: map["ExpiryDate"],ExpiryYear: map["ExpiryYear"]
);
}
Map<String, dynamic> toJson() {
return {"id": id,"CardNumber": CardNumber
,"ExpiryDate": ExpiryDate,"ExpiryYear": ExpiryYear};
}
#override
String toString() {
return 'Profile{id: $id, "CardNumber": CardNumber
,"ExpiryDate": ExpiryDate,"ExpiryYear": ExpiryYear}';
}
}
Future<bool> createProfile(LoginProfile data) async {
response = await client.post(
"$baseUrl",
headers: {'Content-Type': 'application/json; charset=UTF-8'},
body: loginProfileToJson(data),
);
if (response.statusCode == 201) {
return true;
} else {
print(response.body);
}
}
I am meant POST my JSON as below:
{
"Registration": {
"CardNumber":"5105105105105100",
"ExpiryDate":"11",
"ExpiryYear":"2023",
"VerifyCode":"123"
}
}
For some reason, I'm unable to make this work and I need to POST "Registration" as the object like it looks above.

Try with jsonEncode
Future<bool> createProfile(LoginProfile data) async {
response = await client.post(
"$baseUrl",
headers: {'Content-Type': 'application/json; charset=UTF-8'},
body: jsonEncode(loginProfileToJson(data)),
);
if (response.statusCode == 201 || response.statusCode == 200) {
return true;
} else {
print(response.body);
}

Related

How to share image between Spring-Boot and React

I am developing full stack internet-market and i need to send image to my Spring Rest Controller and save it to db. How to do that? I tryed something like that:
setFile(e.target.files && e.target.files[0])
This file is file from <input type="file"/>
After that i send this file to my put method
DishesService.addDish(dish, file)
static async addDish(dish: IDish, file: any) {
try {
await axios.post<IDish>('http://localhost:8080/dishes', dish)
.then(response => {
this.updateDishImage(response.data.id, file)
})
} catch (e) {
console.log('произошла ошибка при добавлении блюда')
}
}
static async updateDishImage(id: number | undefined, image: any) {
try {
await axios.put('http://localhost:8080/dishes/' + id, {}, {
params: {
file: image
}
})
} catch (e) {
console.log('Произошла ошибка при добавлении картинки к блюду')
}
}
And my Spring Boot Put method:
#PutMapping("{dishId}")
public ResponseEntity<DishEntity> updateDishImage(#PathVariable Long dishId, #RequestParam("file") MultipartFile file) {
DishEntity updateDish = dishService.updateDishImage(file, dishId);
return ResponseEntity.ok(updateDish);
}
I get exception:
org.springframework.web.multipart.MultipartException: Current request is not a multipart request
You are missing the headers:
headers: {
"Content-Type": "multipart/form-data",
}
in your axios call
Try this :
#RequestMapping(path = "{dishId}", method = PUT, consumes = { MediaType.MULTIPART_FORM_DATA_VALUE })
public ResponseEntity<DishEntity> updateDishImage(#PathVariable Long dishId, #RequestPart("file") MultipartFile file) {
// your logic
}
You can also encode you images into base64, then send them to the server-side as string.

Flutter: How to sent an array to post request API?

I want to send an array for post API in a flutter.
{
"data":[{"question_id":1,"option_id":2},{"question_id":2,"option_id":6}]
}
I want to send the data like the above.
This is my code:
class Sent {
List<Data> data;
Sent({this.data});
Sent.fromJson(Map<String, dynamic> json) {
if (json['data'] != null) {
data = new List<Data>();
json['data'].forEach((v) {
data.add(new Data.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.data != null) {
data['data'] = this.data.map((v) => v.toJson()).toList();
}
return data;
}
}
class Data {
int questionId;
int optionId;
Data({this.questionId, this.optionId});
Data.fromJson(Map<String, dynamic> json) {
questionId = json['question_id'];
optionId = json['option_id'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['question_id'] = this.questionId;
data['option_id'] = this.optionId;
return data;
}
}
Here is how I sent it to POST API
Future<Sent> saveAnswer() async {
var data = {"question_id": sent[0][0], "option_id": sent[0][1]};
var url = await Network().link("/exercise/1/saveAnswer");
SharedPreferences localStorage = await SharedPreferences.getInstance();
final token = jsonDecode(localStorage.getString('token'));
http.Response response =
await http.post(Uri.parse(url), body: jsonEncode(data), headers: {
'Content-type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token'
});
if (response.statusCode == 200) {
print(response.body);
} else {
print(response.body);
}
}
While this is how I get the question_id and option_id from CustomCheckBoxGroup.
List<dynamic> sent;
CustomCheckBoxGroup(
buttonValuesList: [
[
snapshot.data.result[index].id,
snapshot.data.result[index]
.options[0].id
],
[
snapshot.data.result[index].id,
snapshot.data.result[index]
.options[1].id
],
[
snapshot.data.result[index].id,
snapshot.data.result[index]
.options[2].id
],
[
snapshot.data.result[index].id,
snapshot.data.result[index]
.options[3].id
],
],
checkBoxButtonValues: (values) {
sent = values;
print(values);
print(sent[0][0]);
print(sent[0][1]);
},
)
Please help me. How to sent an array like I want to post request API.
what is wrong with my code.
I suggest using json.encode
List<dynamic> ListData =
[{"question_id":1,"option_id":2},
{"question_id":2,"option_id":6}];
var json = {
'listKey': json.encode(ListData)
}
Simplest way is to encode the list and add it to json.
For example:
List<dynamic> ListData = [{"question_id":1,"option_id":2},{"question_id":2,"option_id":6}];
var json = {
'listKey': json.encode(ListData)
}

ionic 3 acces to json key

i can't access to a key of a json response from a restful web service.
{"_body":"{\"values\": {\"user_id\":\"1\",\"name\":\"fred test\",\"email\":\"fred#test.test\",\"username\":\"fredtest\",\"token\":\"d5f66a06ec809d70d0c52842df8dc0011d7d1ad0f2d56f50d3123da17a2489fe\"}}","status":200,"ok":true,"statusText":"OK","headers":{"pragma":["no-cache"],"content-type":["text/html;charset=UTF-8"],"cache-control":["no-store"," no-cache"," must-revalidate"],"expires":["Thu"," 19 Nov 1981 08:52:00 GMT"]},"type":2,"url":"http://localhost/PHP-Slim-Restful/api/login"}
I would like to acces to 'values' in this function: (this.responseData.values)
login(){
console.log('login'+ this.userData);
// Your app login API web service call triggers
this.authService.postData(this.userData,'login').then((result) => {
this.responseData = result;
console.log('userdata : '+ temp);
if(this.responseData.values){
console.log('response: ' + this.responseData);
localStorage.setItem('userData', JSON.stringify(this.responseData));
this.navCtrl.push(TabsPage);
}
else{
this.showToastWithCloseButton()
}
}, (err) => {
console.log('erreur : '+err);
});
}
I have an error undifined!
Can you help me?
I have used Observable to return json data and using the subscribe function in my method and using response.json() to convert the JSON reponse from RESTful webservices.
My component method,
import {Http, Headers, Response, RequestOptions} from '#angular/http';
import {Observable} from 'rxjs/Rx';
var response = this.service.post('deleteUserDetails/'+this.selectedUserId, null);
response.subscribe((res) => {
var response = res.json();
});
Service Post method,
post(url: string, data : any): Observable<any> {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let options = new RequestOptions({ headers: headers});
return this.http.post(url, data,{headers: headers});
}
I think this might be helpful for your query.
You can make a for in your JSON and access the return values of your post. Something like that.
"this.responseData = result.json();" -> Return JSON. Make a for.
Example:
public postData(data, url: string) {
this.http.post(url, data).toPromise().then(res => {
let responseData = res.json();
if (responseData) {
for (var item of responseData) {
//Implments
}
}
}, (err) => {
});
}

Processing http post array, display undefined

I have the big problem. I want to display this json, but returning undefined value.
{"StatusCode":0,"StatusMessage":"OK","StatusDescription":{ "datas": [
{"sensor_serial":"SensorSerial1", "id":"11E807676E3F30B5"},
{"sensor_serial":"sensorserial2", "id":"11E807679D82841L"},
{"sensor_serial":"sensorserial3", "id":"11E80767A5CD2820"} ]
,"home_id":"11E80768K", "active":0, "homebox_id":"11E8076792BD0164J",
"date_created":"2018-02-01T15:55:54.000Z", "date_modified":null,
"serial_number":"serialn1", "user_id":"3"} }
I use this code in service.ts
public getHomeboxPById(id: string): Observable<HomeboxP> {
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let urlSearchParams = new URLSearchParams();
urlSearchParams.append('home_id', id);
urlSearchParams.append('token', this.auth.getCurrentUser().token);
let body = urlSearchParams.toString();
return this.http.post(Api.getUrl(Api.URLS.getHomeboxPById), body, {
headers: headers
})
.map((response: Response) => {
let res = response.json();
if (res.StatusCode === 0) {
return new HomeboxP(res.StatusDescription[0]);
} else if (res.StatusCode === 1) {
this.auth.logout();
} else {
return new HomeboxP(null);
}
});
}
In ts code I call this method getHomeboxPById, like this
editHomeboxPForm: FormGroup;
homeboxp: HomeboxP;
this.editHomeboxPForm = this.fb.group({
'homebox_id': new FormControl('', Validators.required)
});
}
populateFormHomeboxP() {
this.activatedRoute.params.subscribe(
params => {
this.ws.getHomeboxPById(params['id']).subscribe(
homeboxp => {
console.log(homeboxp); // display undefined
this.homeboxp = homeboxp;
this.editHomeboxPForm.controls['homebox_id'].setValue(homeboxp.homebox_id);
}
);
}
);
}
Please, can you help me, why doesn't work?
{"StatusCode":0,"StatusMessage":"OK","StatusDescription":{ "datas": [
{"sensor_serial":"SensorSerial1", "id":"11E807676E3F30B5"},
{"sensor_serial":"sensorserial2", "id":"11E807679D82841L"},
{"sensor_serial":"sensorserial3", "id":"11E80767A5CD2820"} ]
,"home_id":"11E80768K", "active":0, "homebox_id":"11E8076792BD0164J",
"date_created":"2018-02-01T15:55:54.000Z", "date_modified":null,
"serial_number":"serialn1", "user_id":"3"} }
If this is the response of
this.http.post(Api.getUrl(Api.URLS.getHomeboxPById)
Then issue is res.StatusDescription[0] , it should be res.StatusDescription like :
new HomeboxP(res.StatusDescription);

Handle multipart/form-data with Serverless?

How to handle multipart/form-data with serverless-framework? v.0.5.6
Just tried this:
"requestTemplates": {
"multipart/form-data": {
"httpMethod": "$context.httpMethod",
"body": "$input.json('$')",
"queryParams": "$input.params().querystring",
"headerParams": "$input.params().header",
"headerParamNames": "$input.params().header.keySet()",
"contentTypeValue": "$input.params().header.get('Content-Type')"
},
"application/json": {
"httpMethod": "$context.httpMethod",
"body": "$input.json('$')",
"queryParams": "$input.params().querystring",
"headerParams": "$input.params().header",
"headerParamNames": "$input.params().header.keySet()",
"contentTypeValue": "$input.params().header.get('Content-Type')"
}
}
action.js:
export function respond(event, cb) {
var form = new formidable.IncomingForm();
form.parse(event, function(err, fields, files) {
if (err == null) {
var response = {
status: "true",
data: fields,
error: []
};
return cb(null, response);
} else {
console.log(err);
return cb(null, ApiErrors.errors(402, err['message'] + fields));
}
});
}
But got an error: errorMessage = "Cannot read property 'content-length' of undefined";
I've got this working with serverless by emulating http.ClientRequest and using a form parser tool like formidable.
I'm using lambda-proxy for the API Gateway event configuration.
const Stream = require('stream').Readable;
const Formidable = require('formidable');
module.exports.upload = ( e, ctx, cb ) => {
let form = new Formidable.IncomingForm();
let stream = new Stream();
stream.push( e.body );
stream.push( null );
// NOTE: You'll likely want to toLowerCase() at least 'Content-Type' header key
stream.headers = e.headers;
form.parse( stream, (err, fields, files) => {
// Work with your parsed form results here.
});
}
Well, I couldnt make it as multipart/form-data, so I used base64 string.
action.js:
export function respond(event, cb) {
//console.log('Received event:', JSON.stringify(event, null, 2));
var key = new Date().toISOString().substr(0, 10) + '/' + String(Date.now());
var contentType = event.body["data"].substr(0, event.body["data"].indexOf(';'));
if (!contentType.match(/(\.|\/)(gif|jpe?g|png)$/i)) {
return cb(null, 'invalid content type, gif, jpg, and png supported');
}
var data = new Buffer(event.body["data"].replace(/^image\/\w+;base64,/, ''),'base64');
var params = {
Bucket: 'your-bucket',
Key: key,
Body: data,
ContentEncoding: 'base64',
ContentType: contentType,
ACL: 'public-read'
};
s3.upload(params, function (err, data) {
if (err) {
console.log(err);
return cb(null, ApiErrors.errors(402, err['message']));
} else {
var response = {
status: "true",
data: {
url: urlPrefix + key
},
error: []
};
return cb(null, response);
}
});
}
RequestTemplate:
"requestTemplates": {
"application/json": {
"httpMethod": "$context.httpMethod",
"body": "$input.json('$')",
"header": "$input.params().header.get($header)",
"headerParam": "$input.params().header.keySet()",
"contentType": "$input.params().header.get('Content-Type')"
}
},

Resources