How to send FormData with Dio? - flutter

Hello I am sending a FormData using Dio but when this is sent, the website returns an error
var formData = FormData.fromMap({
"ctl00\$ScriptManager1": "ctl00\$UpdatePanel1",
"__EVENTTARGET" :"ctl00\$cphPage\$productsControl",
"__EVENTARGUMENT" : "",
"__LASTFOCUS" : "",
"PageLoadedHiddenTxtBox" : "Set",
"Language" : "es-MX",
"CurrentLanguage" : "es-MX",
"Currency" : "",
"__VIEWSTATE" :"/sadasd.....",
"__VIEWSTATEGENERATOR" : "C0E71A90",
"ctl00\$txtSearch" : "",
"ctl00\$cphPage\$productsControl\$TopTools\$cbxSortType" : "",
"ctl00\$cphPage\$productsControl\$TopTools\$cbxPageSize" : "-1",
"ctl00\$taxes\$listCountries" : "54",
"__ASYNCPOST" : "true",
" " : ""
});
var dio = Dio();
dio.interceptors.add(InterceptorsWrapper(onRequest: (RequestOptions options) async {
var customHeaders = {
'content-type': 'text/html; charset=utf-8',
'application':'x-www-form-urlencoded',
'Cookie': 'uid=rBQBc2CisZdxWU5XBBmMAg==; ASP.NET_SessionId=tedc4xrih1hk1ykbdzlakuvb; ASPNET_Session=client=BLUR; ShopMSAuth=0102A9A3B88FC919D908FEA90B7DF1D119D908000442004C005500520000012F00FF'
// other headers
};
options.headers.addAll(customHeaders);
return options;
}));
Response response = await dio.post(url, data: formData, options: Options(
contentType: 'text/html; charset=utf-8',
followRedirects: true
));
print(response.data);
When I check the requests by the browser, the requests at the end have as parameters:
__ASYNCPOST :true
:""
Will the form be fine like this?

you can follow this path
var formData = FormData.fromMap({
'name': 'wendux',
'age': 25,
'file': await MultipartFile.fromFile('./text.txt',filename: 'upload.txt')
});
response = await dio.post('/info', data: formData);

Related

Infobip SMS bulk messages API with flutter/dart

My post request doesn't work
I've tried running this but i end up with :
{"requestError":{"serviceException":{"messageId":"UNAUTHORIZED","text":"Invalid logindetails"}}}
This is my code :
data() async {
final client = HttpClient();
final request = await client .postUrl(Uri.parse("https://....api.infobip.com/sms/2/text/advanced")); request.headers.set(HttpHeaders.contentTypeHeader, "{'Authorization':'App ...KEY','Content-Type': 'application/json','Accept': 'application/json'}");
request.write({ '"messages": [{"from": "sms","destinations": [{"to": "..."}],"text": "ABC"}]' });
final response = await request.close();
response.transform(utf8.decoder).listen((contents) {
print(contents);
});
}
I just figured out an answer for this POST request in flutter
makePostRequest(int number) async {
final uri = Uri.parse('https://....api.infobip.com/sms/2/text/advanced');
final headers = {
'Authorization':
'App API-KEY',
'Content-Type': 'application/json'
};
Map<String, dynamic> body = {
"messages": [
{
"from": "SenderID",
"destinations": [
{"to": number}
],
"text": "TEST!"
}
]
};
String jsonBody = json.encode(body);
final encoding = Encoding.getByName('utf-8');
Response response = await post(
uri,
headers: headers,
body: jsonBody,
encoding: encoding,
);
int statusCode = response.statusCode;
String responseBody = response.body;
print(responseBody);
}

Flutter api showing 'Required parameter missing or invalid'

Flutter rest API showing 'Required parameter missing or invalid'
main() async {
final data = {
'customer': {
'first_name': 'Karla',
'last_name': 'Mullins',
'email': 'KarlaMullins#mailinator.com',
'phone': '+15142546011',
'verified_email': true,
'addresses': [
{
'address1': '123 Oak St1',
'city': 'Ottawa1',
'province': 'ON',
'phone': '555-1212',
'zip': '123 ABC',
'last_name': 'Mullins',
'first_name': 'Karla',
'country': 'CA',
}
]
}
};
var json = jsonEncode(data);
String username = 'u';
String password = 'p';
String basicAuth =
'Basic ' + base64Encode(utf8.encode('$username:$password'));
var response = await http.post(url',
headers: <String, String>{
'authorization': basicAuth,
"Accept": "application/json",
},
body: json,
);
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
calling rest api with basic authorisation from flutter dart showing Response status: 400
and Response body: {"errors":{"customer":"Required parameter missing or invalid"}}.
Change Accept into "content-type":"application/x-www-form-urlencoded
Or application/json, depending on your api.

flutter send data to server (statusCode 500)

I am new to flutter and am trying to send data to the server. I followed a tutorial, but it did not work it give me a status code 500:
void signUp() async {
http.Response response = await http.post(
"https://my-shop-server.herokuapp.com/api/v1/users/signup",
body:jsonEncode(<String, String>{
"name" :"test" ,
"email" : "test180#gmail.com" ,
"password" : "qwert" ,
"passwordConfirm" : "qwert"
})
);
print(response.body);
print(response.statusCode);
}
You do not correctly pass the body. You need to jsonEncode your key-value pair like this:
http.Response response = await http.post(
"https://my-shop-server.herokuapp.com/api/v1/users/signup",
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body:jsonEncode(<String, String>{
"name" :"test" ,
"email" : "test180#gmail.com" ,
"password" : "qwert" ,
"passwordConfirm" : "qwert"
});
Please carefully look here.

Cypress: I want to GET data from JSON and pass it as parameter for other tests

I have a POST request for login.
It returns a JSON with an "accessToken".
In order to perform future REST calls I have to use the "accessToken" in the header as Authorization.
So I created a command like:
Cypress.Commands.add('authToken', () => {
it('POST test for Login', function(){
cy.request({
method : 'POST',
url : 'myWebsite',
body: {
"client_id": "DATA1",
"username": "DATA2",
"password": "DATA3"
},
headers:{
'Content-Type' : 'application/json',
'Accept' : 'application/json',
}
}).then(function(response){
// the body returned is a Json which has a parent ticket with a Key = access_token
// HERE I tried different things:
let auth
auth = response.body.ticket.access_token
return auth
// or
cy.wrap(response.body.ticket.access_token)
// or
return response.body.ticket.access_token
....
In the test I want to use the returned access_token:
describe('GET members', function(){
it('GET members', function(){
let val = cy.authToken()
cy.request({
method : 'GET',
url : 'myWEb',
headers:{
'Content-Type' : 'application/json',
'Accept' : 'application/json',
"Authorization" : val,
}
....

How to add Item in Folder present in the list using REST API in SharePoint?

The below code successfully adds items in the list, but I want to add item in the folder which is present in the list using REST API, list name is "Designation" and folder name is "Folder1". What changes should I make to insert item in folder?
$.ajax({
url:"https://brillio446.sharepoint.com/teams/Social2016/work/_api/web/lists/getByTitle('Designation')/items",
method:"POST",
dataType:"json",
data: JSON.stringify({
'__metadata': {'type': 'SP.Data.DesignationListItem' },
'Title': 'D1',
}),
headers: {
"Accept": "application/json;odata=verbose",
"content-type": "application/json; odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
},
success: function(data){
alert("Item added successfully!");
},
error: function(err){
alert("Error while adding item: " + JSON.stringify(err));
}
});
I also find that folder path should be there so I tried this code...
But I got error that 'Path' does no exist in SP.Data.DesigantionListItem
data: JSON.stringify({
'__metadata': {'type': 'SP.Data.DesignationListItem' },
'Title': 'D1',
'Path': '/ServerRelativeUrl of folder',
}),
This is an old question, but search led me here, so adding answer for others.
As Vadim mentioned, /_api/web/lists/getbytitle('ListTitle')/items method does not support adding items to folder.
Instead, you should use /_api/web/lists/GetByTitle('ListTitle')/AddValidateUpdateItemUsingPath method.
Just make sure, you use string values instead of numbers or dates or similar, because it works same as you enter form - parse, validate and save values.
MSDN Reference: Create list item in a folder
Example:
$.ajax({
url:"https://brillio446.sharepoint.com/teams/Social2016/work/_api/web/lists/getByTitle('Designation')/AddValidateUpdateItemUsingPath",
method:"POST",
dataType:"json",
data: JSON.stringify({{
"listItemCreateInfo": {
"FolderPath": { "DecodedUrl": "/ServerRelativeUrl of folder" },
"UnderlyingObjectType": 0
},
"formValues": [
{
"FieldName": "Title",
"FieldValue": "D1"
}
],
"bNewDocumentUpdate": false
}),
headers: {
"Accept": "application/json;odata=verbose",
"content-type": "application/json; odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
},
success: function(data){
alert("Item added successfully!");
},
error: function(err){
alert("Error while adding item: " + JSON.stringify(err));
}
});
It seems it is not supported to specify folder url while creating list item but you could consider the following approach:
create a ListItem resource
get associated File resource and move it into folder
Example
function executeJson(options)
{
var headers = options.headers || {};
var method = options.method || "GET";
headers["Accept"] = "application/json;odata=verbose";
if(options.method == "POST") {
headers["X-RequestDigest"] = $("#__REQUESTDIGEST").val();
}
var ajaxOptions =
{
url: options.url,
type: method,
contentType: "application/json;odata=verbose",
headers: headers
};
if("payload" in options) {
ajaxOptions.data = JSON.stringify(options.payload);
}
return $.ajax(ajaxOptions);
}
function createListItem(listTitle,properties,folderUrl){
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/items";
return executeJson({
"url" :url,
"method": 'POST',
"payload": properties})
.then(function(result){
var url = result.d.__metadata.uri + "?$select=FileDirRef,FileRef";
return executeJson({url : url});
})
.then(function(result){
var fileUrl = result.d.FileRef;
var fileDirRef = result.d.FileDirRef;
var moveFileUrl = fileUrl.replace(fileDirRef,folderUrl);
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getfilebyserverrelativeurl('" + fileUrl + "')/moveto(newurl='" + moveFileUrl + "',flags=1)";
console.log(url);
return executeJson({
"url" :url,
"method": 'POST',
});
});
}
Usage
var listTitle = "Requests"; //list title
var targetFolderUrl = "/Lists/Requests/Archive"; //folder server relative url
var itemProperties = {
'__metadata': { "type": "SP.Data.RequestsListItem" },
"Title": 'Request 123'
};
createListItem(listTitle,itemProperties,targetFolderUrl)
.done(function(item)
{
console.log('List item has been created');
})
.fail(function(error){
console.log(JSON.stringify(error));
});
Gist