C# 如何发送get
时间: 2024-10-23 16:06:22 浏览: 24
在C#中,你可以使用HttpClient类来发送GET请求。以下是简单的步骤:
```csharp
using System;
using System.Net.Http;
class Program
{
static async Task Main(string[] args)
{
try
{
// 创建HttpClient实例
HttpClient client = new HttpClient();
// 设置请求地址
string url = "http://example.com/api/data"; // 替换为你需要的URL
// 发送GET请求
HttpResponseMessage response = await client.GetAsync(url);
// 检查请求是否成功
if (response.IsSuccessStatusCode)
{
// 获取响应内容(通常是JSON)
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("Response Body: " + responseBody);
}
else
{
Console.WriteLine($"Request failed with status code: {response.StatusCode}");
}
client.Dispose(); // 关闭连接释放资源
}
catch (Exception ex)
{
Console.WriteLine($"Error occurred: {ex.Message}");
}
}
}
```
在这个例子中,我们首先创建一个`HttpClient`实例,然后设置请求地址并调用`GetAsync`方法发起GET请求。如果请求成功,我们会读取响应内容并打印出来。记得在请求完成后关闭`HttpResponseMessage`。
阅读全文
相关推荐


















