{
public static str callExternalAPI(str url)
{
System.Net.Http.HttpClient httpClient;
System.Net.Http.HttpResponseMessage responseMessage;
str responseData;
httpClient = new System.Net.Http.HttpClient();
// Set a timeout for the HTTP client (e.g., 30 seconds)
httpClient.Timeout = new System.TimeSpan(0, 0, 30);
{
// Send the GET request
responseMessage = httpClient.GetAsync(url).Result;
responseMessage.EnsureSuccessStatusCode();
responseData = responseMessage.Content.ReadAsStringAsync().Result;
}
catch (Exception::CLRError)
{
// Handle any errors that occur during the request
ClrObject clrEx = ClrInterop::getLastException();
error(strFmt("API call failed: %1", clrEx.ToString()));
error(strFmt("Exception Type: %1", clrEx.GetType().ToString()));
error(strFmt("Exception Message: %1", clrEx.Message()));
}
finally
{
// Dispose of the HttpClient
httpClient.Dispose();
}
}
{
try
{
str result = GetAPIClient::callExternalAPI("https://api.restful-api.dev/objects/7");
info("API Response: " + result);
System.Type jObjectType = CLRInterop::getType("Newtonsoft.Json.Linq.JObject");
System.Object jObject = jObjectType.getMethod("Parse").Invoke(null, [result]);
info("Parsed JSON successfully.");
str name = CLRInterop::getAnyTypeForObject(jObjectType.getMethod("get_Item").Invoke(jObject, ["name"])).ToString();
info("Name: " + name);
System.Object dataObject = jObjectType.getMethod("get_Item").Invoke(jObject, ["data"]);
info("Data object extracted.");
int year = CLRInterop::getAnyTypeForObject(dataObject.GetType().getMethod("get_Item").Invoke(dataObject, ["year"]));
real price = CLRInterop::getAnyTypeForObject(dataObject.GetType().getMethod("get_Item").Invoke(dataObject, ["price"]));
str cpuModel = CLRInterop::getAnyTypeForObject(dataObject.GetType().getMethod("get_Item").Invoke(dataObject, ["CPU model"])).ToString();
str hardDiskSize = CLRInterop::getAnyTypeForObject(dataObject.GetType().getMethod("get_Item").Invoke(dataObject, ["Hard disk size"])).ToString();
info(strFmt("Year: %1, Price: %2, CPU Model: %3, Hard Disk Size: %4", year, price, cpuModel, hardDiskSize));
APIData apiData;
// ttsBegin;
apiData.clear();
apiData.Name = name;
apiData.Year = year;
apiData.Price = price;
apiData.CpuModel = cpuModel;
apiData.HardDiskSize = hardDiskSize;
apiData.insert();
// ttsCommit;
}
catch (Exception::CLRError)
{
ClrObject clrEx = ClrInterop::getLastException();
error(strFmt("API call failed in main method: %1", clrEx.ToString()));
}
}