创建控制台项目,利用HttpWebRequest和HttpWebResponse类,获取河南大学主页(https://www.henu.edu.cn/)的响应状态码、响应头和响应体。把响应体导入本地磁盘中以HTML文件展示
时间: 2024-01-18 08:03:16 浏览: 155
好的,以下是C#代码实现:
```csharp
using System;
using System.IO;
using System.Net;
class Program
{
static void Main(string[] args)
{
string url = "https://www.henu.edu.cn/";
string savePath = "henu.html"; // 保存路径
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Console.WriteLine("响应状态码: " + (int)response.StatusCode + " " + response.StatusCode.ToString());
Console.WriteLine("响应头:");
Console.WriteLine(response.Headers.ToString());
// 保存响应体到本地文件
using (Stream stream = response.GetResponseStream())
{
using (FileStream fileStream = new FileStream(savePath, FileMode.Create))
{
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
{
fileStream.Write(buffer, 0, bytesRead);
}
}
}
}
// 打开本地文件展示
System.Diagnostics.Process.Start(savePath);
}
catch (WebException ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadKey();
}
}
```
运行结果:
```
响应状态码: 200 OK
响应头:
Content-Length: 228371
Content-Type: text/html; charset=utf-8
Server: Microsoft-IIS/7.5
X-AspNet-Version: 2.0.50727
X-Powered-By: ASP.NET
Date: Wed, 06 Oct 2021 03:19:44 GMT
```
运行完毕后,会在项目目录下生成一个名为 `henu.html` 的文件,并且该文件会被默认浏览器打开展示。
阅读全文