我有一个使用 System.Net.HttpWebRequest
的 Powershell 脚本与远程主机通信。
我创建请求,相应地设置属性并调用 getresponse()
和 getresponsestream()
从服务器读取整个响应到一个字符串。只要服务器以“200 OK”消息响应,就可以正常工作。
如果服务器以“400 Bad Request”或任何其他错误代码响应,getresponse()
和 getresponsestream()
抛出异常并且不返回任何内容。我的问题是我需要的响应 header 中包含更详细的错误信息,因此我可以进行自己的错误处理。
我怎样才能检索到这个 400 Bad Request 信号?
最佳答案
编辑 :我一开始误解了这个问题,但事实证明您可以使用 HttpWebResponse.GetResponseHeader()
检索响应 header 方法。如果发生异常,HttpWebRequest.GetResponse()
方法返回 $null
,并且必须使用这段代码来检索HttpWebResponse对象,这样才能调用GetResponseHeader()
在上面:
# If an exception occurs, get the HttpWebResponse object from the WebException object
$HttpWebResponse = $Error[0].Exception.InnerException.Response;
我很确定你会想坚持使用
System.Net.HttpWebRequest
而不是 System.Net.WebClient
目的。这是一个示例,类似于您可能已经拥有的示例:# Create a HttpWebRequest using the Create() static method
$HttpWebRequest = [System.Net.HttpWebRequest]::Create("http://www.google.com/");
# Get an HttpWebResponse object
$HttpWebResponse = $HttpWebRequest.GetResponse();
# Get the integer value of the HttpStatusCode enumeration
Write-Host -Object $HttpWebResponse.StatusCode.value__;
GetResponse() 方法返回
HttpWebResponse
对象,它有一个名为 StatusCode
的属性,它指向 HttpStatusCode
中的一个值.NET 枚举。一旦您获得对枚举的引用,我们将使用 value__
属性以获取与返回的枚举值关联的整数。如果你从
GetResponse()
得到一个空值方法,那么您需要在 catch {..} 块中读取最新的错误消息。 Exception.ErrorRecord
属性应该是最有帮助的。try {
$HttpWebResponse = $null;
$HttpWebRequest = [System.Net.HttpWebRequest]::Create("http://www.asdf.com/asdf");
$HttpWebResponse = $HttpWebRequest.GetResponse();
if ($HttpWebResponse) {
Write-Host -Object $HttpWebResponse.StatusCode.value__;
Write-Host -Object $HttpWebResponse.GetResponseHeader("X-Detailed-Error");
}
}
catch {
$ErrorMessage = $Error[0].Exception.ErrorRecord.Exception.Message;
$Matched = ($ErrorMessage -match '[0-9]{3}')
if ($Matched) {
Write-Host -Object ('HTTP status code was {0} ({1})' -f $HttpStatusCode, $matches.0);
}
else {
Write-Host -Object $ErrorMessage;
}
$HttpWebResponse = $Error[0].Exception.InnerException.Response;
$HttpWebResponse.GetResponseHeader("X-Detailed-Error");
}
http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx
http://msdn.microsoft.com/en-us/library/system.net.httpstatuscode.aspx
http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.aspx
关于.net - System.Net.HttpWebRequest::GetResponse() 中的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9543818/