C# 获取网页接口内容:HttpClient 示例教程 - 代码示例
"C# 如何打开网页,获取网页接口内容:在 C# 中,可以使用 `HttpClient` 类来打开网页并获取网页接口。以下是一个示例:\n\ncsharp\nusing System;\nusing System.Net.Http;\nusing System.Threading.Tasks;\n\nclass Program\n{\n static async Task Main(string[] args)\n {\n // 创建 HttpClient 实例\n using (HttpClient client = new HttpClient())\n {\n try\n {\n // 发送 GET 请求并获取响应\n HttpResponseMessage response = await client.GetAsync(\"https://example.com/api\");\n\n // 确保请求成功\n response.EnsureSuccessStatusCode();\n\n // 读取响应内容\n string responseBody = await response.Content.ReadAsStringAsync();\n\n // 处理响应内容\n Console.WriteLine(responseBody);\n }\n catch (HttpRequestException ex)\n {\n // 处理异常\n Console.WriteLine(\"请求发生异常: {ex.Message}\");\n }\n }\n }\n}\n\n\n在上面的示例中,我们使用 `HttpClient` 类的 `GetAsync` 方法来发送 GET 请求,并使用 `ReadAsStringAsync` 方法来读取响应内容。通过 `EnsureSuccessStatusCode` 方法,我们可以确保请求成功。
原文地址: https://www.cveoy.top/t/topic/p1cT 著作权归作者所有。请勿转载和采集!