Test WebClient API call

与世无争的帅哥 提交于 2019-12-12 05:39:25

问题


I have the following PowerShell script that makes an API Rest GET call.

$FullURL = "http://test.net/config/server/$($env:COMPUTERNAME)?format=test"
$API = New-Object System.Net.WebClient
$APIData = $API.DownloadString($FullURL)
Set-Content -Value $APIdata -Path $APIDataFile -Force

The call is dependent on the local hostname in the URI. It gets the data and exports to a text file as a backup. The problem - the API host maybe down or no information available for the host which will cause all sorts of errors in the script (this is a small part of the script as it adds the data to an XML file).

How do I add logic to the script to test the API call first, if the successfully then continue with making the API call?

It must work for PowerShell 2.0 because of windows 2003 hosts. API is gives an error 404 code if the theres no data.


回答1:


You need to use a try/catch block. WebClient should raise an exception when the download isn't successful. Try something like:

$FullURL = "http://test.net/config/server/$($env:COMPUTERNAME)?format=test"
try {
    $API = New-Object System.Net.WebClient
    $APIData = $API.DownloadString($FullURL)
    Set-Content -Value $APIdata -Path $APIDataFile -Force
}
catch [Net.WebException] {
    # Do whatever you want if an exception is raised    
}


来源:https://stackoverflow.com/questions/37279103/test-webclient-api-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!