I have a flutter app and I'm using back4app.com and Parse RESTful api to register my users, I have read their docs about logging in users but I dont know how to pass my username and password in URL parameters as JSON encoded :
I tried this method:
Future <void>loginMethod(String username,String password) async {
var url = Uri.parse('https://myshoppingapp.b4a.io/login/$username:$password');
final response = await http.get(url, headers: {
'X-Parse-Application-Id': kParseApplicationId,
'X-Parse-REST-API-Key': kParseRestApiKey,
'Content-Type': 'application/json'
},);
final exData = jsonDecode(response.body);
print(exData);
but I've got some errors
Don't use the GET method while sending your personal data to the server.
GET method data is sent data to the server followed by the URL like append with URL request which will be seen to everyone like below.
var url = Uri.parse('https://myshoppingapp.b4a.io/login/$username:$password');
This is how your personal data can be readable from a URL in a GET Method.
'https://myshoppingapp.b4a.io/login/Mehran#metra.org:abcd12345'
For login requests, we should use the POST method. Because our login data is secure which needs security. When using the POST method the data is sent to the server in a bundle.
Future loginMethod(String username,String password) async {
var res = await http.post(Uri.parse('https://myshoppingapp.b4a.io/login/'),
body: {"username": username, "password": password});
print('res : ${res.body}');
if (res.statusCode == 200){ final exData = jsonDecode(res.body);
print(exData);
return res.body;
} else{
final exData = jsonDecode(res.body);
print(exData);
return res.statusCode;
}
}
for HTTP basic authentication
final loginUrl = Uri(scheme: 'https', host: 'example.com', port: 8080, userInfo: 'username:password')
http.get(loginUrl)
but pass username and password via url is not recommended cause it's not safe.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication#access_using_credentials_in_the_url
so you should do it by using post formdata.
Related
I have to post this json data:
JSON.stringify(dataRest) is:
{"Ds_MerchantParameters":"eyJEU19NRVJDSEFOVF9BTU9VTlQiOiI3Myw4NCIsIkRTX01FUkNIQU5UX0NVUlJFTkNZIjoiOTc4IiwiRFNfTUVSQ0hBTlRfTUVSQ0hBTlRDT0RFIjoiMzUyNDM0NDM1IiwiRFNfTUVSQ0hBTlRfT1JERVIiOiIwMDAwMDAwMDA3NjUiLCJEU19NRVJDSEFOVF9JRE9QRVIiOiIxODExNzViOTBjNDM2ZDNlZDQ3ODg4OWEyMjdjNjI2Yjc0MDBiOTEyIiwiRFNfTUVSQ0hBTlRfVEVSTUlOQUwiOiIxIiwiRFNfTUVSQ0hBTlRfVFJBTlNBQ1RJT05UWVBFIjoiMCJ9","Ds_Signature":"X5IoP/ssIy+8gBFbD9znLoz4dFOH/mWRjMCaE/8kq65XJJVLywT05wVXE4Fqbbo6","Ds_SignatureVersion":"HMAC_SHA256_V1"}
To this endpoint https://sis-t.redsys.es:25443/sis/rest/trataPeticionREST
Using RestSharp (v107) (or httpclient).
I post above data to my api LaunchRequest via ajax:
$.ajax({
method: 'POST',
url: localhost + 'api/Redsys/LaunchRequest',
contentType: 'application/json',
data: JSON.stringify(dataRest)
}).done(function (response) {
console.log(response);
}).fail(function (error) {
console.error(error.status + '\n' + error.responseText);
});
This is the api that receive the above data and launch request to the endpoint:
[HttpPost("LaunchRequest")]
public async Task<string> LaunchRequest(DataRest dataRest)
{
string strDataRest = JsonConvert.SerializeObject(dataRest);
var client = new RestClient("https://sis-t.redsys.es:25443/");
var request = new RestRequest("sis/rest/trataPeticionREST", Method.Post);
request.RequestFormat = DataFormat.Json;
request.AddBody(strDataRest);
var response = await client.ExecuteAsync(request);
if (response.IsSuccessful)
{
return response.Content;
}
else
{
return response.ErrorMessage;
}
}
What is wrong?
Allways receive this message:
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. (sis-t.redsys.es:25443)
Thank you in advance for your help.
I think one of my mistakes is serialize dataRest.
LaunchRequest should be like this:
[HttpPost("LaunchRequest")]
public async Task<string> LaunchRequest(DataRest dataRest)
{
var client = new RestClient("https://sis-t.redsys.es:25443/");
var request = new RestRequest("sis/rest/trataPeticionREST", Method.Post);
request.RequestFormat = DataFormat.Json;
request.AddBody(dataRest);
var response = await client.ExecuteAsync(request);
if (response.IsSuccessful)
{
return response.Content;
}
else
{
return response.ErrorMessage;
}
}
I don't know if the steps I follow in LaunchRequest are correct, but anyway I always get this error message:
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. (sis-t.redsys.es:25443)
Thank you very much again for the help you can give me.
Your issue is most probably not related to RestSharp as it looks like a connection issue between the host running your API, and the external API host.
From the other issues, I am not sure why you deserialize the object just to serialize it back. You can just do this:
var request = new RestRequest("sis/rest/trataPeticionREST", Method.Post);
request.AddJsonBody(dataRest);
You also need to avoid creating the client for each request. Create a single client instance in the controller's constructor.
It's all described in the documentation by the way.
I have flutter app where user input data and that data is stored on mysql.
Everything works perfect on my PHP, HTML on web. But in flutter I can't get session of user.
Future getData() async {
var url = 'https://azer.maverus.ba/api/read.php';
var response = await http.get(Uri.parse(url));
return json.decode(response.body);
}
I have that script and it read only data that I type inside flutter. And can't read data from database from curent user.
You have to add header to pass Authorization key to the API check the code below
Future getData() async {
var url = 'https://azer.maverus.ba/api/read.php';
var response = await http.get(Uri.parse(url),headers: <String, String>{
"Authorization" : "YOUR KEY HERE"
});
return json.decode(response.body);
}
I tried to follow this: https://flutter.dev/docs/cookbook/networking/send-data but code it's not working and i dont know why. Can someone help me and tell me what I have wrong or some video I could use to implement those functions correctly?
What I want to do is to send all the information from a form to the server.
My code: https://github.com/guillemrh/urbix/blob/master/lib/screens/signup_screen_administrador.dart
Thank you
The endpoint http://ec2-52-47-176-18.eu-west-3.compute.amazonaws.com/reg/us/ does not support application/json content type. According to this stackoverflow answer http package only has 3 types: String, List or Map. Try this:
var mapData = new Map<String, dynamic>();
mapData['firstname'] = firstname;
mapData['lastname'] = lastname;
mapData['username'] = username;
mapData['email'] = 'email;
mapData['passw'] = passw;
map['user_type'] = 'Administrador';
final http.Response response = await http.post(
'http://ec2-52-47-176-18.eu-west-3.compute.amazonaws.com/reg/us/',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: mapData
),
);
Also security wise. When dealing with user information such as name, password, and email. Please use HTTPS. You can achieve this on AWS by throwing a load balancer in front of the API server.
I am trying to send a parameter using Angular2 POST to my Python/Tornado back-end which returns a JSON object. The parameters are being sent properly but at the Python side, it is returning 400 POST missing arguments error. I am using Ionic 2/Angular2 in the front-end and Python/Tornado server.
Angular2 code is as follows:
Here content is a variable containing HTML table
let body = JSON.stringify({content: content});
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
this.http.post(url, body, options).map(res => res.json()).subscribe(data => {
console.log(data)
}, error => {
console.log(JSON.stringify(error));
});
Python code is as follows:
def post(self):
print self.request.arguments
print self.get_argument('content')
self.finish(dict(result="ok", data=content))
Here is the error:
[W 160824 06:04:30 web:1493] 400 POST /test (182.69.5.99): Missing argument content
[W 160824 06:04:30 web:1908] 400 POST /test (182.69.5.99) 1.67ms
Your Angular2 code looks reasonable, however your Python code is wrong, because you are treating the request as x-www-form-urlencoded. You have to access the JSON string through the request.body property:
data = tornado.escape.json_decode(self.request.body)
See https://stackoverflow.com/a/28140966/2380400 for an answer to a similar question.
You should maybe try to use something like URLSearchParams() with an URLencoded content type. I don't know much about Tornado but I am using ASP controllers and it works fine.
See Angular2 Documentation : https://angular.io/docs/ts/latest/api/http/index/URLSearchParams-class.html
Watch the following authentication example I am using :
controllerURL: string = "/APIConnexion";
login(aLogin: string, aMdp: string) {
// parameters definition (has to have the same name on the controller)
let params = new URLSearchParams();
params.set("aLogin", aLogin);
params.set("aMdp", aMdp);
// setup http request
let lHttpRequestBody = params.toString();
let lControllerAction: string = "/connexion";
let lControllerFullURL: string = this.controllerURL + lControllerAction;
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });
// call http
return this.http.post(lControllerFullURL, lHttpRequestBody, options)
.map((res: any) => {
// data received as JSON
let data = res.json();
// Do something with your data
}
).catch(this.handleError);
}
i want to know how i can get a json response from my node.js server and display the response on my web page
below is the request and reponse in json code
var request = require("request"),
username = req.body.username,
password = req.body.password,
url = "https://api.ecoachsolutions.com/main.php?ecoachsignin=1&server=remote&user="+username+"&pass="+password;
console.log("url is "+url);
request.get(
{
url : url
},
function (error, response, body) {
// Do more stuff with 'body' here
if (!error && response.statusCode == 200) {
var json_body = JSON.parse(body);
console.log(json_body);
var msg = json_body.profile.user;//this is the message i want to show on my web page(msg)
console.log(msg); // get json response
}
}
);
You will first have to register express to use ejs:
app.engine('.html', require('ejs').__express);
then you can use res.render and pass your data to the view
res.render('index.html', {msg: json_body.profile.user});
After that you can access that via the EJS
<%= msg %>
If you need a working example, a good one can be found at:
https://github.com/strongloop/express/tree/master/examples/ejs