csharp使用HttpWebResponse
时间: 2023-07-22 13:59:04 浏览: 64
在C#中,可以使用HttpWebRequest和HttpWebResponse类来发送HTTP请求并获取响应。
以下是一个简单的示例代码,用于发送GET请求并获取响应:
```csharp
using System;
using System.IO;
using System.Net;
class Program
{
static void Main()
{
// 创建HttpWebRequest实例并设置请求URL
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.example.com");
// 发送请求并获取响应
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
// 获取响应流
using (Stream stream = response.GetResponseStream())
{
// 读取响应内容
using (StreamReader reader = new StreamReader(stream))
{
string responseBody = reader.ReadToEnd();
Console.WriteLine("响应内容: " + responseBody);
}
}
}
}
}
```
在以上代码中,首先创建HttpWebRequest实例,并设置请求的URL。然后,使用GetResponse方法发送请求并获取响应。接着,通过GetResponseStream方法获取响应流,并使用StreamReader读取响应内容。
你可以根据自己的需求进行调整和扩展,例如发送POST请求、设置请求头、传递参数等。记得在使用完HttpWebResponse后将其释放,以释放资源。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)