我有一个Powershell脚本,它使用System.Net.HttpWebRequest与远程主机通信。
我创建了请求,相应地设置了属性,并调用getresponse()和getresponsestream()来读取从服务器到字符串的整个响应。只要服务器以“200OK”消息响应,就可以正常工作。
如果服务器响应“400Bad Request”或任何其他错误代码,getresponse()和getresponsestream()将抛出异常,不返回任何内容。我的问题是在响应头中包含了更详细的错误信息,这是我需要的,这样我就可以进行自己的错误处理。
我怎样才能检索到这个400错误的请求信号?
发布于 2012-03-04 00:21:16
编辑:一开始我误解了这个问题,但事实证明您可以使用HttpWebResponse.GetResponseHeader()方法检索响应头。如果发生异常,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
发布于 2012-03-03 16:30:13
有没有尝试过try和catch语句?这对我来说很好。
例如:
$webclient = new-object system.net.webclient
try {
$domain = $webclient.downloadstring("http://xrsolis.com") # get a non existent domain
} catch {
write-host "domain inaccessible"
}https://stackoverflow.com/questions/9543818
复制相似问题