我正在使用标准的[System.Net.WebRequest]
类来返回给定URL的HTTP响应代码。
URL指向内部Web应用程序服务器,该服务器返回“401 Unauthorized”错误。这实际上是正常的,因为运行脚本的服务帐户没有应用程序的有效帐户。但是,我对该网站的回应更感兴趣。但是,我假设这是一个HTTP响应本身,所以我可以管理它,但它返回为null值。
$HTTP_Request = [System.Net.WebRequest]::Create('http://google.com')
$HTTP_Response = $HTTP_Request.GetResponse()
$HTTP_Status = [int]$HTTP_Response.StatusCode
使用“0”参数调用“GetResponse”的异常:“远程服务器返回错误:(407)需要代理验证。”
(我在这个例子中使用了Google,我们的服务器无法访问外部网站)。
因此,我无法在代码中获得$HTTP_Status = [int]$HTTP_Response.StatusCode
,因为它不会接受400个错误作为代码。
如何在查询中接受401(或此示例中的407)?
谢谢
得到它了!
try{
$request = $null
$request = Invoke-WebRequest -Uri "<URL>"
}
catch
{
$request = $_.Exception.Response
}
$StatusCode = [int] $request.StatusCode;
$StatusDescription = $request.StatusDescription;
你可以做到:
$HTTP_Request = [System.Net.WebRequest]::Create('http://google.com')
$HTTP_Request.Method = "GET"
$HTTP_Request.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
[System.Net.HttpWebResponse]$HTTP_Response = $HTTP_Request.GetResponse()
Try {
$HTTP_Status = [int]$HTTP_Response.StatusCode
}
Catch {
#handle the error if you like, or not...
}
If ($HTTP_Status -eq 200) {
Write-Host "Good Response"
} Else {
Write-Host "Site Down or Access Denied"
}
# If you got a 404 Not Found, the response will be null so can't be closed
If ($HTTP_Response -eq $null) { } Else { $HTTP_Response.Close() }
你错过了认证片:
$HTTP_Request.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
我重新阅读了你的帖子,因为你的服务帐户无法访问你正在访问的URL(实际上并不是google.com
......你应该放myserver.com
... grr),你实际上永远不会得到200,但总会得到一个例外。这是一种不好的做法,因为您不必寻找200,而是必须始终专门查找401
或407
未经授权的异常状态代码,如果代码/响应更改为其他内容,那么它才会被视为失败 - 但从技术上讲,它总是失败,因为它从未到达过网站!如果您打算故意使用您的服务帐户无法访问的网站,它会掩盖潜在的问题。如果您的服务帐户被授予访问权限,则必须更新您的代码。