c# HttpWebRequest
时间: 2024-09-18 17:15:04 浏览: 99
在C#中,HttpWebRequest是一个用于发送HTTP请求的核心类,它属于System.Net命名空间。当你需要从Web服务器获取数据(如GET请求)、提交数据(如POST请求)或者执行其他HTTP操作时,你会创建一个HttpWebRequest对象,并设置其属性来指定请求的目标URL、方法(GET、POST等)、头部信息以及所需的数据。
例如,创建一个简单的GET请求的代码可能会像这样:
```csharp
using System;
using System.IO;
using System.Net;
public class HttpRequestExample {
public static void Main() {
try {
// 创建HttpWebRequest对象
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://example.com/api/data");
// 设置请求方法
request.Method = "GET";
// 发送请求并获取响应
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
if (response.StatusCode == HttpStatusCode.OK) {
// 读取响应内容
using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
string data = reader.ReadToEnd();
Console.WriteLine("Response Data: " + data);
}
} else {
Console.WriteLine($"Error with status code {response.StatusCode}");
}
}
} catch (Exception e) {
Console.WriteLine($"Error occurred: {e.Message}");
}
}
}
```
阅读全文
相关推荐


















