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.
Related
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.
I am working in NodeJS with CouchDB 2.1.1.
I'm using the http.request() method to set various config settings using the CouchDB API.
Here's their API reference, yes, I've read it:
Configuration API
Here's an example of a working request to set the logging level:
const http = require('http');
var configOptions = {
host: 'localhost',
path: '/_node/couchdb#localhost/_config/',
port:5984,
header: {
'Content-Type': 'application/json'
}
};
function setLogLevel(){
configOptions.path = configOptions.path+'log/level';
configOptions.method = 'PUT';
var responseString = '';
var req = http.request(configOptions, function(res){
res.on("data", function (data) {
responseString += data;
});
res.on("end", function () {
console.log("oldLogLevel: " + responseString);
});
});
var data = '\"critical\"';
req.write(data);
req.end();
}
setLogLevel();
I had to escape all the quotes and such, which was expected.
Now I'm trying to get CouchDb to accept a setting for compaction.
The problem is that I'm attempting to replicate this same request to a different setting but that setting doesn't have a simple structure, though it appears to be "just a String" as well.
The CouchDB API is yelling at me about invalid JSON formats and I've tried a boatload of escape sequences and attempts to parse the JSON in various ways to get it to behave the way I think it should.
I can use Chrome's Advanced Rest Client to send this payload, and it is successful:
Request Method: PUT
Request URL: http://localhost:5984/_node/couchdb#localhost/_config/compactions/_default
Request Body: "[{db_fragmentation, \"70%\"}, {view_fragmentation, \"60%\"}, {from, \"23:00\"}, {to, \"04:00\"}]"
This returns a "200 OK"
When I execute the following function in my node app, I get a response of:
{"error":"bad_request","reason":"invalid UTF-8 JSON"}
function setCompaction(){
configOptions.path = configOptions.path+'compactions/_default';
configOptions.method = 'PUT';
var responseString = '';
var req = http.request(configOptions, function(res){
res.on("data", function (data) {
responseString += data;
});
res.on("end", function () {
console.log("oldCompaction: " + responseString);
});
});
var data = "\"[{db_fragmentation, \"70%\"}, {view_fragmentation, \"60%\"}, {from, \"23:00\"}, {to, \"04:00\"}]\"";
req.write(data);
req.end();
}
Can someone point at what I'm missing here?
Thanks in advance.
You need to use node's JSON module to prepare the data for transport:
var data = '[{db_fragmentation, "70%"}, {view_fragmentation, "60%"}, {from, "23:00"}, {to, "04:00"}]';
// Show the formatted data for the requests' payload.
JSON.stringify(data);
> '"[{db_fragmentation, \\"70%\\"}, {view_fragmentation, \\"60%\\"}, {from, \\"23:
00\\"}, {to, \\"04:00\\"}]"'
// Format data for the payload.
req.write(JSON.stringify(data));
I have a .net application which sends the following request to a node js server:
System.Net.Http.HttpClient client = new HttpClient();
client.PostAsync("http://some_url.com", some_string);
What I want to do is extract some_string from the post request on my server.
The post request comes in but I am unsure how to get the string from it. What I do:
if (req.method == 'POST') {
var body = '';
req.on('data,', function (data) {
body += data;
console.log(data);
});
But this does not do anything. I can see the length of my data in the req.headers property but where is the data itself? Am I doing this correctly?
I am working on a "Skill" for the new Amazon ECHO. The skill will allow a user to ask Alexa for information on the status and performance of an Enphase solar system. Alexa will respond with results extracted from the JSON based Enphase API. For example, the user could ask,
"Alexa. Ask Enphase how much solar energy I have produced in the last week."
ALEXA <"Your array has produced 152kWh in the last week.">
Problem is it has been years since I've programmed in JavaScript and this is my first time using AWS Lambda. I have not been very successful finding any information on how to embed a JSON query to a third party server within AWS Lambda function. Here is a relevant section of code in my Lambda function:
/**
* Gets power from Enphase API and prepares speach
*/
function GetPowerFromEnphase(intent, session, callback) {
var Power = 0;
var repromptText = null;
var sessionAttributes = {};
var shouldEndSession = false;
var speechOutput = "";
//////////////////////////////////////////////////////////////////////
// Need code here for sending JSON query to Enphase server to get power
// Request:
// https://api.enphaseenergy.com/api/v2/systems/67/summary
// key=5e01e16f7134519e70e02c80ef61b692&user_id=4d7a45774e6a41320a
// Response:
// HTTP/1.1 200 OK
// Content-Type: application/json; charset=utf-8
// Status: 200
// {"system_id":67,"modules":35,"size_w":6270,"current_power":271,
// "energy_today":30030,"energy_lifetime":59847036,
// "summary_date":"2015-03 04","source":"microinverters",
// "status":"normal","operational_at":1201362300,
// "last_report_at":1425517225}
//////////////////////////////////////////////////////////////////////
speechOutput = "Your array is producing " + Power + " kW, goodbye";
shouldEndSession = true;
// Setting repromptText to null signifies that we do not want to reprompt the user.
// If the user does not respond or says something that is not understood, the session
// will end.
callback(sessionAttributes,
buildSpeechletResponse(intent.name, speechOutput, repromptText,
shouldEndSession));
}
Some guidance would be much appreciated. Even if someone could point me in the right direction. Thanks!
Request is a very popular library for handling http requests in node.js. Here is an example of a POST using your data:
var request = require('request');
request({
url: 'https://api.enphaseenergy.com/api/v2/systems/67/summary',
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
key: '5e01e16f7134519e70e02c80ef61b692',
user_id: '4d7a45774e6a41320a'
})
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log('BODY: ', body);
var jsonResponse = JSON.parse(body); // turn response into JSON
// do stuff with the response and pass it to the callback...
callback(sessionAttributes,
buildSpeechletResponse(intent.name, speechOutput, repromptText,
shouldEndSession));
}
});
I don't have an example of ECHO/Alexa but here is an example of Lambda calling out to get weather data to send it to Slack
I'm a complete beginner in Node.js and I wanted to consult something I could not figure out.
Even though I've researched extensively I could not find any method to receive JSON request without using a plugin. I will be using it to program a mobile application API. But even though I've incluede parameter request I cannot reach the content by using request.body, or request.data. The request I'm trying to make is;
{
"id":"123"
}
And my failing code is;
var http = require('http');
function onRequest(request, response){
console.log("Request: "+request.data+"\n");
response.writeHead(200, {"Content-Type":"text/plain"});
response.write("Hello, World");
response.end();
}
http.createServer(onRequest).listen(8888);
The problem here is that you're not listening to the request events to let you know that you have data, and then parsing the data. You're assuming that request has request.data.
It should be:
var http = require('http');
function onRequest(request, response){
var data = '';
request.setEncoding('utf8');
// Request received data.
request.on('data', function(chunk) {
data += chunk;
});
// The end of the request was reached. Handle the data now.
request.on('end', function() {
console.log("Request: "+data+"\n");
response.writeHead(200, {"Content-Type":"text/plain"});
response.write("Hello, World");
response.end();
});
}
http.createServer(onRequest).listen(8888);
See this for the documentation for the methods that request contains.