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
Related
Future<String> loginUser(User user) async {
var body = jsonEncode({
'strlogin': user.email,
});
Response response = await post(SeguriSignAPIURL.loginUser,
headers: headers,
body: body);
if (response.statusCode == 200) {
var decode = jsonDecode(response.body);
return decode['token'];
} else {
print(response.reasonPhrase);
return '';
}
Hey! When I make this Post call on Postman I get a result, however when I run this code on flutter I get a 400 error. My headers:
final headers = {
'Content-Type': 'application/json; charset=UTF-8',
"Accept": "application/json",
};
Postman:
In Postman you do the request using form-data, but in your Flutter code, you pass json-encoded body.
You either need to use form-data in Flutter or update your server code to accept json content type.
I am integrating Stripe in my flutter app, want to create payment intent using http POST request having mention here. But I am constantly receiving this error. Tried many thing!
{
"error": {
"code": "parameter_unknown",
"doc_url": "https://stripe.com/docs/error-codes/parameter-unknown",
"message": "Received unknown parameter: {\"amount\":2,\"currency\":\"usd\"}",
"param": "{\"amount\":2,\"currency\":\"usd\"}",
"type": "invalid_request_error"
}
}
My api function is this:
Future<Map<String, dynamic>> createPaymentIntent(int amount) async {
try {
var url = "https://api.stripe.com/v1/payment_intents";
var body = json.encode({
"amount": amount,
"currency": 'usd'
});
var headers = {
'Content-type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
'authorization': 'Bearer '+stripeSecret
};
await http.post(url, body: json.encode(body), headers: headers, encoding: Encoding.getByName("utf-8")).then((response) {
if(response.statusCode == 200){
print(response.body);
return json.decode(response.body);
}
else{
return response.reasonPhrase;
}
});
} catch (e) {
return e.message;
}
}
Note: 'Content-type': 'application/x-www-form-urlencoded' is necessary for this.
You are sending a JSON encoded body to the Stripe API, but the Stripe API expects a form-encoded request body:
Our API has predictable resource-oriented URLs, accepts form-encoded request bodies, returns JSON-encoded responses, and uses standard HTTP response codes, authentication, and verbs.
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.
I am trying to send a Map of string and list which is like:
Map<String, List<int>> results = {
"tags": [5 , 10]
}
Object headers = {
HttpHeaders.authorizationHeader: "Bearer ${accessToken}",
"Accept": "application/json",
};
and I post that like this:
post() {
return http
.post("$resource/$baseName/$id$query",
headers: headers,
body: results ,
)
.then((http.Response response) {
return json.decode(response.body);
}).catchError((err) {
print(err);
});
}
and I got this error:
type 'List<int>' is not a subtype of type 'String' in type cast
also I guess that I should send
Map<String,String>
but I have
Map<String, List<int>>
I try many things but am also new to flutter so I got confusing a lot
Thanks if someone can help me .
EDIT:
i try with dio
try {
Response response =
await Dio().post("$resource/$baseName/$id$query", data: {
'tags': [1, 2]
},
options: Options(headers: headers)
);
print(response);
} catch (e) {
print(e);
}
Are you encoding your data when you send it? Try encoding your data before sending it. You specify your header to accept application/json, but you might not be sending json.
See: https://api.dartlang.org/stable/2.5.0/dart-convert/jsonEncode.html
import 'dart:convert';
Map<String, List<int>> results = {
"tags": [5 , 10]
};
final encodedResults = jsonEncode(results); // send these encoded results.
How do you create this map?
Wouldn't it be possible to start a .toString in the list?
Note: I suggest using the Dio plugin, it makes it much easier to work with requests in webServices, in my opinion of course!
Take a look here: https://pub.dev/packages/dio
Map<String, List<int>> results = {
"tags": [5 , 10]
}
var dio = Dio();
FormData data = FormData();
final local = '$baseName/$id$query'
dio.options.baseUrl = source;
data.add('tags', results.toString);
try{
final response = await dio.post(local, data: data, options: Options(
method: 'POST',
responseType: ResponseType.json
));
final body = jsonDecode(response.data);
print(body);
}catch(e){
print(e);
return e;
}
I try to do a simple post request with axios.
My code snippet:
const getOauthToken = async () => {
try {
const headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'X-ProxyPass' : '...',
}
const data = {
...
}
return await axios.post('/oauth2/token', data, {headers: headers});
} catch (error) {
throw new Error(`Unable to get an authentication token. Reason ${error}`);
}
};
This call fails with http 400. When I set the headers as default with
axios.defaults.headers.post['X-ProxyPass'] = '...';
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
then it works.
Found the solution in the documentation of axios.
If I use "application/x-www-form-urlencoded", I have to use querystring to serialize in the needed format.
return await axios.post('/oauth2/token', querystring.stringify(data), {headers: headers});
But why it works, when I set the headers as default headers i still mysterious.