Servicenow HTTP get call failure
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-12-2024 11:41 AM
I'm working on a ServiceNow custom operation script to fetch the serial number for CIs from an API endpoint. The script successfully makes an HTTP GET request and receives a valid JSON response. However, I encounter an issue while parsing the JSON response.
Here is the script I'm using:
this.httpCall = Packages.com.snc.sw.commands.HttpCallHandler;
var logger = Packages.com.snc.sw.log.DiscoLog.getLogger("IP Phone Get Call");
// Initialize variables
var url = "https://example.com/api/v1/Device/10.199.81.79";
var serial = "";
var phone = "10.199.81.79";
var httpClient = new httpCall();
var ciType = CTX.getAttribute('pattern_cit_id');
var ArrayList = Packages.java.util.ArrayList;
var result = "";
try {
// Make HTTP GET request
logger.info("Making HTTP GET request to URL: " + url);
var response = httpClient.invoke(CTX, url, 'GET', null, null, ciType, $headers, $required_authentication);
if (response) {
var responseBody = response.getBody();
logger.info("HTTP Response Body: " + responseBody);
if (JSUtil.notNil(responseBody)) {
try {
var jsonResponse = JSON.parse(responseBody);
logger.info("Parsed JSON Response: " + JSON.stringify(jsonResponse));
// Extract serial number from JSON response
serial = jsonResponse.serial;
result = phone + "," + serial + "\n";
} catch (parseEx) {
logger.error("Error parsing JSON response for IP address " + phone + ": " + parseEx.message);
result = phone + ",\n";
}
} else {
logger.error("Response body is null or empty for IP address " + phone);
result = phone + ",\n";
}
} else {
logger.error("Response is null for IP address " + phone);
result = phone + ",\n";
}
} catch (ex) {
// Handle any exceptions during HTTP request
logger.error("Error occurred for IP address " + phone + ": " + ex.message);
result = phone + ",\n";
}
// Set the result in the context attribute
CTX.setAttribute('response', result);
The log shows the response body correctly, but the script still throws an error when attempting to parse the JSON. Here is the log output:
HTTP response: {"name":"DM","ipAddress":"10.199.81.79","serial":"FOC2739J0U1"}
Error parsing JSON response for IP address 10.199.81.79: undefined
Can someone help me understand why the JSON parsing is failing even though the response looks correct? Any advice or suggestions would be greatly appreciated.
note:- Here i have hardcoded one ip address for testing but later i will send a array of ip address to hit url one by one with each ip and save the serial number