- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
07-26-2017 10:07 AM
I am working on a scoped application that sends an HTTP POST via REST using RESTMessageV2 via an asynchronous business rule.
Assume the current.partner.data_in_request field contains the following string value:
{
"input": {
"context": {
"system": {
"dialog_request_counter": 170,
"dialog_stack": {
"dialog_node": ""
},
"dialog_turn_counter": 170
}
},
"text": "Hey"
}
}
Also assume the following code snippet:
var rm = new sn_ws.RESTMessageV2();
rm.setRequestBody(current.partner.data_in_request);
I'm getting an HTTP 200 response code from the web service; however, it isn't properly reading the request body. I've tried parsing it (i.e. JSON.parse(current.partner.data_in_request)), I've tried stringifying it (i.e. JSON.stringify(current.partner.data_in_request)), and I've tried forcing string conversion (i.e. current.partner.data_in_request.toString()), but nothing seems to work.
My question is, is it possible to set the setRequestBody value as JSON in ServiceNow, or do I need to use some other structure for the request body?
Solved! Go to Solution.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
12-27-2019 10:23 PM
You need to first convert your JSON object to sting and then set to the request-body.
Please try the following -
//==
var req = new sn_ws.RESTMessageV2();
req.setEndpoint('https://--- your end-point here');
req.setHttpMethod('POST');
//Authentication
var username = user; // your user-name
var pw = password; //your password
req.setBasicAuth(user,password);
//Set Headers
req.setRequestHeader('Content-Type','application/json');
//Create payload (JSON with key-value pair)
var myObj = {
"input": {
"context": {
"system": {
"dialog_request_counter": 170,
"dialog_stack": {
"dialog_node": ""
},
"dialog_turn_counter": 170
}
},
"text": "Hey"
}
} ;
//Convert the object to string and set it to Request Body-
req.setRequestBody(JSON.stringify(myObj));
//Execute the request
req.execute(); // if successful, it will return http status = 200 or 201,
// Get handle on response-body
var responseBody = response.getBody();
//Get http status (Success: 200/201 or Failure: 400/401/500)
var httpStatus = response.getStatusCode();
// Do the rest of the processing, if httpStatus = 200 || 201
if(httpStatus == 200 || httpStatus == 201){
//Parse response-body
var parsedJSON = JSON.parse(responseBody);
current.field1 = parsedJSON.something1;
current.field2 = parsedJSON.something2
//.... etc.
}
Please mark it as 'Correct', if it works.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
10-26-2021 07:20 AM
Yeah it works