Jus*_*tin 2 .net powershell httpwebrequest httpwebresponse
我有一个System.Net.HttpWebRequest用于与远程主机通信的Powershell脚本.
我创建请求,相应地设置属性并调用getresponse()并getresponsestream()从服务器读取整个响应到字符串.只要服务器以"200 OK"消息响应,这就可以正常工作.
如果服务器有一个"400错误的请求"或任何其他错误代码,响应getresponse()并getresponsestream()抛出异常和返回任何结果.我的问题是我需要的响应头中包含更详细的错误信息,因此我可以自己进行错误处理.
我如何能够检索此400 Bad Request信号?
编辑:我最初误解了这个问题,但事实证明你可以使用该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;
Run Code Online (Sandbox Code Playgroud)
我很确定你会坚持使用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__;
Run Code Online (Sandbox Code Playgroud)
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");
}
Run Code Online (Sandbox Code Playgroud)
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