“ The remote server returned an error: (401) Unauthorized ”

痴心易碎 提交于 2020-01-03 05:33:11

问题


I am trying to verify if my URLs get a response. in other words, i am trying to check if the authentication has succeeded approaching the site.

I used:

$HTTP_Request = [System.Net.WebRequest]::Create('http://example.com')
$HTTP_Response = $HTTP_Request.GetResponse()
$HTTP_Status = [int]$HTTP_Response.StatusCode

If ($HTTP_Status -eq 200) { 
    Write-Host "Site is OK!" 
} Else {
    Write-Host "The Site may be down, please check!"
}

$HTTP_Response.Close()

and I got the response:

The remote server returned an error: (401) Unauthorized.

but after that i got:

site is ok

Does that mean it's ok? If not, what is wrong?


回答1:


You are getting OK because you rerun your command and $HTTP_Response contains an object from a previous, successful run. Use try/catch combined with a regex to extract correct status code(and clean up your variables):

$HTTP_Response = $null
$HTTP_Request = [System.Net.WebRequest]::Create('http://example.com/')
try{
    $HTTP_Response = $HTTP_Request.GetResponse()
    $HTTP_Status = [int]$HTTP_Response.StatusCode

    If ($HTTP_Status -eq 200) { 
        Write-Host "Site is OK!" 
    }
    else{
        Write-Host ("Site might be OK, status code:" + $HTTP_Status)
    }
    $HTTP_Response.Close()
}
catch{
    $HTTP_Status = [regex]::matches($_.exception.message, "(?<=\()[\d]{3}").Value
    Write-Host ("There was an error, status code:" + $HTTP_Status)
}

.Net HttpWebRequest.GetResponse() throws exceptions on non-OK status codes, you can read more about it here: .Net HttpWebRequest.GetResponse() raises exception when http status code 400 (bad request) is returned




回答2:


I think the following happens:

You are trying to query a web page using GetResponse(). This fails, so the following Statements run with the values you set in a previous run. This leads to the Output you described.

I personally tend to use the invoke-webrequest in my scripts. This makes it easier to handle Errors, because it supports all Common Parameters like Erroraction and so on.



来源:https://stackoverflow.com/questions/23760070/the-remote-server-returned-an-error-401-unauthorized

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