Submit array in http flutter - flutter

This is how I post the two values to server using postman.
How should I write in http?
var url = "xxx";
var response = await http.post(url, headers: headers, body: {
....
'all_receivers': adminList.toString(),
'commence_time': endTime, // this no issue
...
});
I pass adminList which is [725,607], but get error:
Error
all_receivers id [725 is invalid. all_receivers id 607] is invalid.

You create a json and pass it
or
You can create and array of strings
You can simply resolve that by casting your List to String.
By casting the token list using toString() method you will get a String like this "['token1','token2']"
Here's the modified code:
List<String> adminList=["725","607"]; // how to pass 725,607
var response = await http.post(url, headers: headers, body: {
'all_receivers': adminList.toString(), // how to pass 725,607
}

try to pass with jsonEncode
var response = await http.post(url, headers: headers, body: JsonEncode({
'all_receivers': adminList,
});
print(response);

This is how I fixed
final receivers = adminList.join(",");
final body = {'all_receivers':receivers}
http.post(url', body: body);

Related

How to put parametrs in url with queryParamets in GET-request in dart?

I have an API and I need to put non-optional parametrs in GET-request and I did this:
Future<List<FlightBook>> fetchFlights(int mv_id) async {
String basicAuth =
'Basic ' + base64Encode(utf8.encode('$username:$password'));
print(basicAuth);
final queryParameters = {
"mv_id" : mv_id,
};
var response = await http.get(Uri.parse("http:/mylink/getFlights.php?fmt=json&{$queryParameters}" ), headers: <String, String>{'authorization': basicAuth});
var jsonResponse = convert.jsonDecode(response.body) as List;
return jsonResponse.map((e) => FlightBook.fromJson(e)).toList();
}
but when I tried to get some data from this I got the blank screen with no values and after that I did request like so and everything works fine:
'var response = await http.get(Uri.parse("http:/mylink/getFlights.php?fmt=json&mv_id=1'
How can I put this parametr inside my link if I need not only the first elemnt but all elements?
Let's try out with this
final queryParameters = {
"mv_id" : mv_id,
"fmt" : "json",
};
var uri = Uri(scheme: "http", host: "/mylink/getFlights.php", queryParameters:queryParameters );
var response = await http.get(uri, headers: <String, String>{'authorization': basicAuth});
Your string interpolation is wrong. The $ goes outside the braces.
You could do: "http:/mylink/getFlights.php?fmt=json&${queryParameters}"
But in this case, you don't need the curly braces, so I would do
"http:/mylink/getFlights.php?fmt=json&$queryParameters"
I agree with the other response on how to add the query parameters, but wanted to show why your version failed in one case and worked in the other.

How to send data when content type is "x-www-form-urlencoded"?

The content type is x-www-form-urlencoded, the image below shows the data I need to send:
In the case, data must be combined with & and =, how should I do in this case?
String body="des=${div}&kr_desc=`{title=${titleKr}&context=${contextKr}}`&en_desc=`{title=${titleEn}&context=${contextEn}}`&jp_desc=`{title=${titleJp}&context=${contextJp}}`&ch_desc=`{title=${titleCh}&context=${contextCh}}`";
http.Response response = await http.post(Uri.parse(url),
headers: {
"Content-Type":"application/x-www-form-urlencoded",
},
body:body
);
That's the way I thought of it, but of course it didn't work. Help!
First create object with key pair value, then you can pass data with http post method. post(Uri.parse(URL), body: bodyobject);
Future<Map> postdata() async {
final bodyobject= {"des": val1,"kr_desc":val2,"title":val3};
final responce = await post(Uri.parse(URL), body: bodyobject);
return jsonDecode(responce.body);
}

Response body empty API

My response.body return empty like this: Response.body: []
It was supposed to return the param like Response.body:["CodVenda":4057}]
static Future<List<Produto>> iniciaVenda(codVenda) async {
var url = 'http://192.168.0.112:4343/inicia_venda.php';
Map<String, String> headers = {};
final params = {"CodVenda": codVenda};
print("> Params: $params");
print("> Pedido Post POST: $url");
final response = await http.post(url, body: params, headers: headers);
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
List list = convert.json.decode(response.body);
final produtos =
list.map<Produto>((map) => Produto.fromJson(map)).toList();
var retornoResponse = false;
I get the data from a API and then I wanted to start the sell but it returns empty.
Could it be a problem in API?
Actually, you need to pass body data with JSON encoded. That may be the main problem.
final response = await http.post(url, body: jsonEncode(params), headers: headers);
You can read more from the official document.

Post array using http in flutter

Anyone know how to post array using http?
var headers = {"Accept": "application/json"};
var url = "https://...."
var response = await http.post(url,
body: {
....
},
I have a param named commentList. I need to pass comment[0], comment[1]... inside body.
How to use for loop inside the body???
for(var i in list){
"comments"+"["+index+"]" = i;
index ++;
}
Here the postman key and value
if you need to combine comments for specific reason you can do like this.
List commentList = ['comment1','comment2','comment3'];
Map<String, dynamic> body;
combine them:
String comments ='';
commentList.forEach((comment){
comments +=comment+' ';
});
body = {'combinedComments':comments};
then post :
var headers = {"Accept": "application/json"};
var url = "https://...."
var response = await http.post(url,
body: this.body);
or just use json encode to convert your list to string;
Map<String,dynamic> body = {'comments' :jsonEncode(commentList)};
and use this as body to post.
I managed to fix it.
int count = 0;
var url = "https://xxx";
var response = await http.post(url,
body: {
for (var i in list) 'comments[${count++}]':i,
....
},
headers: headers);

Invalid Header Name In Flutter HTTP Request

I have a login page where i am trying to send a login request to my backend. But I get an Unhandled Exception: Invalid header field name. Here is my submit function
submit() async {
var res = await LoginAPI().loginData(
{'email': _emailController.value, 'password': _passwordController.value});
var body = json.decode(res.body);
print(body);
}
Then in my LoginAPI class here is my loginData function that makes the call to the backend
import 'dart:convert';
import 'package:http/http.dart' as http;
class LoginAPI {
final String _url = "http://10.0.2.2:8000/api/";
Map<String, String> headers = {"Content-type": "application/json"};
loginData(data) async {
var fullUrl = _url + "v1/users/login";
return await http.post(
fullUrl,
body: jsonEncode(data),
headers: headers
);
}
}
Here is my request through postman
Here is my response through postman
When I make the same request with Postman i get the response I am supposed to get. What Am i doing wrong?
try this
Map<String, String> headers = {"Content-type": "application/json", "Accept": "application/json",};
It looks from your postman request that you are just sending form data (not a json encoded body). package:http will form encode the body for you (and add the content type header) if you do the following:
return await http.post(
fullUrl,
body: data,
);
So i was able to solve the issue. The issue was with my CORS middleware on my server. I just made some changes and it worked fine. So if anyone has this issue just know it has nothing to do with flutter but most probably CORS