Vertx client for sending get request with parameters - vertx-httpclient

I am writing client in Vertx for sending get request with two string parameters but i am receiving empty list from server. If i write request to another service which is on the same path but this service is not receiving any parameters the response is ok and the data is properly returned. The problem is with mapping the parameter on server side with .addQueryParam the parameter is not mapped well on server side. any help?
WebClient client = WebClient.create(vertx);
client
.get(80, "localhost", "/mainpath/path1")
.addQueryParam("startDate", "1459926000")
.addQueryParam("endDate", "1459926900")
.send(ar -> {
if (ar.succeeded()) {
HttpResponse<Buffer> response = ar.result();
JsonArray body = response.bodyAsJsonArray();
System.out.println("Received response with status code " + response.statusCode() + " with body " + body.toString());
} else {
System.out.println("Something went wrong " + ar.cause().getMessage());
}
});
}

Related

Solace nodejs api to retrieve message from message spool Queue

While doing connect through the Nodejs api to the Solace message persistence queue, we encounter error:
{"message":"Consumer is not supported by router for this client","name":"OperationError","subcode":3,"reason":null}
on using the Solace Node.js API sample to connected to the Persistence Message Queue with the Web Message URI using soladmin.
consumer.connect = function (argv) {
if (consumer.session !== null) {
consumer.log('Already connected and ready to consume messages.');
return;
}
// extract params
//if (argv.length < (2 + 3)) { // expecting 3 real arguments
if (argv.length < 4) {
consumer.log('Cannot connect: expecting all arguments' +
'[<protocol://host[:port]>, <client-username>, <message-vpn>, <client-password>].\n' +
'Available protocols are ws://, wss://, http://, https://');
process.exit();
}
var hosturl = argv[0] //argv.slice(2)[0];
consumer.log('Connecting to Solace message router using url: ' + hosturl);
//var usernamevpn = argv.slice(3)[0];
var username = argv[1]//usernamevpn.split('#')[0];
consumer.log('Client username: ' + username);
var vpn = argv[2]//usernamevpn.split('#')[1];
consumer.log('Solace message router VPN name: ' + vpn);
var pass = argv[3]//argv.slice(4)[0];
// create session
try {
consumer.session = solace.SolclientFactory.createSession({
// solace.SessionProperties
url: hosturl,
vpnName: vpn,
userName: username,
password: pass,
});
} catch (error) {
consumer.log(error.toString());
}
The message "Consumer is not supported by router for this client" indicates that the issue is on the remote end.
Check if the client-profile allows the client to receive guaranteed messages. Otherwise, there may be a problem with the message spool that prevents the message broker from providing guaranteed messaging service.
The code snippet in the question is for initiating a connection only, and has nothing to do with connecting to the queue. The operation that failed should be
consumer.messageConsumer.connect();

In Swift, URLSession.shared.dataTask sometimes work and sometimes not

client: swift, xcode 8.3
server: nodejs, express, mongodb
In client side, it first send login request (username & password) to server, upon receive a valid token, it proceeds to the next screen to send another request to get a list of books.
The strange point is that, for the second request for books, sometimes it works - if with debug mode and a number of breakpoints proceeding "slowly", while sometimes it does not work - if proceed the breakpoints not such slow or without them. I repeated a number of times and figured out this pattern.
Here is the piece of code which send request - millions of thanks!!!
let url = URL(string: "http://" + SERVER_IP + ":" + PORT + "/books")
print("Query:>> url: ")
print(url)
var request = URLRequest(url: url!)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request) {(data, response, error) in
print("Query>> response from loadBooks")
if let data = data,
let json = try? JSONSerialization.jsonObject(with: data, options: []) {
var books = [Book]()
if let array = json as? [Any] {
for i in 0...array.count-1 {
var bookJson = array[i] as? [String: Any]
let b = Book(json: bookJson!)
books.append(b!)
}
}
print ("Query>> \(books.count)" + " books loaded, callback completion")
completion(books)
}
}
task.resume()
Console output when the request is not successful:
Query:>> url: Optional(localhost:3001/books)
2017-09-07 15:31:45.173596+0800 SimplyRead[76273:2379182] [] nw_endpoint_flow_service_writes [1.1 ::1.3001 ready socket-flow (satisfied)] Write request has 4294967295 frame count, 0 byte count Query>> response from loadBooks
2017-09-07 15:51:41.210732+0800 SimplyRead[76273:2390856] [] tcp_connection_write_eof_block_invoke Write close callback received error: [89] Operation canceled

Use nlapiRequestURL to make a request to a Service

How do you use nlapiRequestURL to make a request to a service? My attempt below is failing with the error: UNEXPECTED_ERROR (output from NetSuites script execution log).
My service is set to run without login and works correctly when I directly access it through a browser using its url. Its just the request through nlapiRequestURL thats failing.
Any idea what could be going wrong?
// This code executes in Account.Model.js (register function)
// I am using my own netsuite user credential here
var cred = {
email: "MY_NETSUITE_EMAIL"
, account: "EXXXXX" // My account id
, role: "3" // Administrator
, password: "MY_NETSUITE_PASSWORD"
};
var headers = {"User-Agent-x": "SuiteScript-Call",
"Authorization": "NLAuth nlauth_account=" + cred.account + ", nlauth_email=" + cred.email +
", nlauth_signature= " + cred.password + ", nlauth_role=" + cred.role,
"Content-Type": "application/json"};
var payload = {
type: 'is_email_valid'
, email: 'spt015#foo.com'
};
// A raw request to the service works fine:
// http://mywebsite.com/services/foo.ss?type=is_email_valid&email=spt015#foo.com
// Error occurs on next line
var response = nlapiRequestURL(url, payload, headers);
You are attempting to call a non-Netsuite url with Netsuite authentication headers. You do not need that unless for some reason of your own you have implemented NS-style authorization on your service.
nlapiRequestURL does not automatically format a payload into a query string. If your service takes a posted JSON body then you need to call JSON.stringify(payload) e.g
var response = nlapiRequestURL(url, JSON.stringify(payload), headers);
If your service needs a query string like in your example then you need to construct a query string and append it to your service url. e.g.
var qs = '';
for(var k in payload) qs += k +'='+ uriEncodeComponent(payload[k]) +'&';
var response = nlapRequestURL(url +'?'+ qs.slice(0,-1), null, headers);
I would suggest changing your nlapiRequestURL to a GET instead of POST, and add the parameters to the url instead. Your function call will look like this instead.
nlapiRequestURL(url, null, headers, "GET")

Error sending request from Azure Function

I have an Azure Function that I have configured that listens for incoming messages to an Azure Service Bus. I can receive the messages without a problem. But when I try to route the request onto another service for processing, I am getting an error stating that the POST data is empty.
public static void Run(BrokeredMessage message, TraceWriter log)
{
log.Info($"C# ServiceBus queue trigger function processed message: {message.MessageId}");
if (message != null)
{
//MessageObjectEntity is a custom object
Common.Entities.MessageObjectEntity messageObject = message?.GetBody<Common.Entities.MessageObjectEntity>();
string msgType = messageObject?.MessageType;
var msgContent = messageObject?.MessageContent; // MessageContent is of type object to allow any object to be sent
using (var client = new HttpClient())
{
string url = $"http://mycompany.azurewebsites.net/api/routingtasks?formname={msgType}";
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(subscriber, token);
HttpContent content = new StringContent((string)msgContent, Encoding.UTF8, "application/json");
var response = client.PostAsync(new Uri(url), content); // at this point content is valid
// I am getting a BadRequest returned here as the target service has not received the POST data
// that was sent in via the content variable
}
log.Info("Completing message.");
}
It appears that the POST data sent in the variable content is not received despite it being sent.
UPDATE
When I inspect the JSON sent to my Azure Function in the logger it looks like this.
{"FormName":"UpdateMileage","FormData":[{"Key":"enteredmileage","Value":100},{"Key":"todaysdate","Value":"01/01/2017"}],"Profile":{"EmailAddress":"unittest#mycompany.co.uk","ID":9999999}}
Which doesn't work.
But if I hard code the following JSON from my Azure Function it works correctly (the double quotes are needed to escape the back-slashes).
"\"{\\\"FormName\\\":\\\"UpdateMileage\\\","\\\"FormData\\\":"[{\\\"Key\\\":\\\"enteredmileage\\\",\\\"Value\\\":100},"{\\\"Key\\\":\\\"todaysdate\\\",\\\"Value\\\":\\\"01/01/2017\\\"}],"\\\"Profile\\\":"{\\\"EmailAddress\\\":\\\"unittest#mycompany.co.uk\\\","\\\"ID\\\":9999999}}\""
The problem therefore appears to be the formatting of the JSON that is being sent from my Azure Function, but I don't how I would convert my JSON into this format.
The problem was caused by the fact that I was sending JSON to my ASP.NET Web API service, but sending it as a string type. This is wrong.
The following article explains the correct approach when sending JSON data as a POST request.

Node-red "no response object"

I'm trying to create a http get node that takes form data and then creates an http post to another web site using a rest API. I'm able to get the http call to return the correct payload however the http response node is giving a "no response object" error in the debug tab and the client never returns. Do I specifically need to do something to pass the response object so the call sends the correct response object to the http response node?
Here is the flow:
[{"id":"7011e7a9.8fee18","type":"http request","name":"","method":"use","ret":"obj","url":"","x":499,"y":84,"z":"51693a88.ae96c4","wires":[["efea497c.1015b8"]]},{"id":"589f2a18.a760d4","type":"function","name":"","func":"var myprocess = context.global.process;\nmyprocess.env.NODE_TLS_REJECT_UNAUTHORIZED = \"0\";\nvar dev_url = \"https://website.com:22411/central/api/qracore/browses?browseId=mfg:gp239\";\n \nvar msg = {\n \"method\" : \"GET\",\n \"url\" : dev_url,\n \"headers\" : {\n \"Authorization\": \"Basic abWZnQHFhZC5jb206=\",\n \"Origin\" : \"mybox.com\"\n }\n};\n \nreturn msg;","outputs":1,"noerr":0,"x":323,"y":154,"z":"51693a88.ae96c4","wires":[["7011e7a9.8fee18"]]},{"id":"9f65b624.609a48","type":"debug","name":"","active":true,"console":"false","complete":"payload","x":810,"y":211,"z":"51693a88.ae96c4","wires":[]},{"id":"38e4c04d.c71b4","type":"http in","name":"","url":"/workOrders","method":"get","swaggerDoc":"","x":152,"y":190,"z":"51693a88.ae96c4","wires":[["589f2a18.a760d4"]]},{"id":"e5ee54b2.1a11a8","type":"http response","name":"","x":770,"y":96,"z":"51693a88.ae96c4","wires":[]},{"id":"efea497c.1015b8","type":"function","name":"","func":"var newMsg = { payload: msg.payload };\nreturn newMsg;","outputs":1,"noerr":0,"x":582,"y":214,"z":"51693a88.ae96c4","wires":[["e5ee54b2.1a11a8","9f65b624.609a48"]]}]
The key is to pass it from node to the other. You do that by using the req and the res from the msg to pass to the output.
var newMsg = { payload: msg.payload };
//return [msg, newMsg];
newMsg.user = msg.req.body["user"];
newMsg.req = msg.req;
newMsg.res = msg.res;
return newMsg;

Resources