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.
Related
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);
}
I am trying to recall the API request after getting the refresh token from the API.
Having issue in recall the same API request.
It shows invalid access token error while running this api.
how to fix this issue.
How to recall the get API request to get the access token .
Future<http.Response> _getAPIById(String pathURL) async {
try {
final Uri uri = Uri.http(ApiConstants.baseUrl, pathURL);
print(uri);
print(accessToken);
http.Response response = await _ioClient.get(
uri,
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + accessToken!
},
);
if (response.statusCode != 200) {
print("Status Not Ok");
print(response.body);
if (response.statusCode == 401) {
await refreshAccessToken();
print("Status code 401 called");
Future.delayed(
Duration(milliseconds: 1000),
() async {
return await _ioClient.get(
uri,
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
'x-access-token': 'Bearer ' + accessToken!
},
);
});
}
} else if (response.statusCode == 200) {
print("Ok");
print(response.body);
return response;
}
print(response.body);
return response;
} catch (e) {
print(e);
throw Exception('Error occurred');
}
}
Future<String> refreshAccessToken() async {
Map<String, String> requestBody = {'refresh_token': refreshToken!};
final response = await http.post(
Uri.parse(
ApiConstants.baseUrlWithHttp + ApiConstants.refreshAccessToken),
body: requestBody,
headers: {
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded",
},
encoding: Encoding.getByName("utf-8"));
print("refreshAccessToken");
print(response.body);
if (response.statusCode == 200) {
status = true;
var decodedData = jsonDecode(response.body);
accessToken = decodedData['accessToken'];
refreshToken = decodedData['refreshToken'];
}
return response.body;
}
How to fix this issue? Help me with the solution.
Remove last return response; and unnecessary Future.delayed. Something like this could work:
Future<http.Response> _getAPIById(String pathURL) async {
try {
http.Response response = await _ioClient.get(
Uri.http(ApiConstants.baseUrl, pathURL),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + accessToken!
},
);
if (response.statusCode == 401) {
await refreshAccessToken();
return await _ioClient.get(
uri,
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
'x-access-token': 'Bearer ' + accessToken!
},
);
} else {
return response;
}
} catch (e) {
throw Exception('Error occurred');
}
}
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);
I am trying to send a http.post request with multiple variables.
var acc = {
'acc_type': 'normal',
'time': 'Jan 27',
};
var what = await http.post(
'http://localhost:7200/api/activity/addactivity',
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(
<String, dynamic>{
'userId': 'aaa111',
'location': 'hellooooo',
'acc': acc
},
),
);
When I remove acc: acc, Flutter sends requests. However, I need to send var acc value to the server in order to post it. I tried to encode it to JSON the http.post() function. It seems not working. How can I send the object as part of the post request?
This will work.
import 'dart:convert';
//....
var what = await http.post(
'http://localhost:7200/api/activity/addactivity',
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: json.encode(
<String, dynamic>{
'userId': 'aaa111',
'location': 'hellooooo',
'acc': acc
},
),
);
var acc = {
'acc_type': 'normal',
'time': 'Jan 27',
};
var what = await http.post(
'http://localhost:7200/api/activity/addactivity',
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body:(
<String, dynamic>{
'userId': 'aaa111',
'location': 'hellooooo',
'acc': acc.toString(),
},
),
);
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,
}
....