用HttpWebRequest请求时,获取响应的状态码

时间:2022-12-29 13:50:12

直接上一段代码

[TestMethod]
public void TestWebPage()
{
	var httpStatusCode = 200;
	try
	{
		var req = WebRequest.Create( "http://10.168.94.116/Default.aspx" );

		req.Method = "GET";
		/// 获取响应流
		var rsp = req.GetResponse() as HttpWebResponse;	// 最好能捕获异常302的HttpException,然后再处理一下。在Data中取键值 Location
		httpStatusCode = (int)rsp.StatusCode;
	}
	catch ( WebException ex )
	{
		var rsp = ex.Response as HttpWebResponse;
		Assert.AreNotEqual( null, rsp, ex.Message );
		httpStatusCode = (int)rsp.StatusCode;
	}
	if ( httpStatusCode == 200 )
		Assert.AreEqual<int>( 200, httpStatusCode );
	else
		Assert.AreEqual<int>( 403, httpStatusCode );

}


怎么取,很明显了。

如果你还想要取中断了的流数据,可以在捕获取的WebException类中,取他的Response,来继续读取数据流内容