65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 .NET WebClient 进行 HTTP GET 请求

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.17/5 (13投票s)

2009年3月2日

CPOL

2分钟阅读

viewsIcon

255558

downloadIcon

8217

使用 WebClient 和 StreamReader 在 C# 中执行 HTTP GET 请求的方法。

引言

使用 .NET 开发的乐趣之一在于,我们以前需要自己编写的大量基础工作现在已经成为框架的一部分。 在本文中,我将展示使用 WebClientStreamReader 在 C# 中执行 HTTP GET 请求的方法。 我将在未来的文章中使用这些方法。

首先,让我们介绍 StreamStreamReader,它们都可以在 System.IO 命名空间中找到。 StreamReader 实现了一个 TextReader,默认情况下从流(源)读取 UTF-8 字符,这使其非常适合从 URI 读取。 请注意,StreamReader 与读取字节的 Stream 不同。

为了向 URI 发送和接收数据,.NET 提供了 WebClient 类,该类可以在 System.Net 命名空间中找到。 提供了几种方法来使我们能够同步和异步地发送和接收文件和数据。 我们在这里感兴趣的方法是 OpenRead(URI),它将 URI 的数据作为 Stream 返回。

动手编码

从我们的 URI 读取的基本代码可以用三行实现。 我们创建 WebClient 实例,从 WebClient 创建一个 Stream,然后读取到 StreamReader,直到文件末尾,如下所示

using System.IO;
using System.Net;

String URI = "http://somesite.com/somepage.html";

WebClient webClient = new WebClient();
Stream stream = webClient.OpenRead(URI);
String request = reader.ReadToEnd();

在运行完这段代码后,somepage.html 的内容将位于 request 字符串变量中。 这很好,但我们假设这里的请求是无错误的……即,没有抛出异常。 鉴于 .NET 中异常处理非常容易,没有理由不利用它……尽管从经验来看,似乎并非每个人都持有相同的观点……

让我们将我们的 Stream 请求包装在一个 try-catch 循环中。 我们可以捕获一个 WebException 来清楚地识别出了什么问题,并很好地处理它。

try
{
    WebClient webClient = new WebClient();
    Stream stream = webClient.OpenRead(URI);
    String request = reader.ReadToEnd();
}
catch (WebException ex)
{
    if (ex.Response is HttpWebResponse)
    {
        switch (((HttpWebResponse)ex.Response).StatusCode)
        {
            case HttpStatusCode.NotFound:
                response = null;
                break;

            default:
                throw ex;
        }
    }
}

我们可以通过在 WebClient/Stream 周围包装 using(...) 来进一步优化代码,但这超出了本文的范围。

身份验证

如果您的 URI 需要身份验证,可以在调用 OpenRead 方法之前将 NetworkCredential 添加到 WebClient 引用,如下所示

WebClient webClient = new WebClient();
webClient.Credentials = new NetworkCredential(username, password);
Stream stream = webClient.OpenRead(URI);

上述示例的一个实际应用是从 Twitter 检索您最新的推文列表。 您需要传递您的用户名和密码才能访问该 feed。 下载示例使用此作为演示,因此您需要添加您自己的 Twitter 用户名和密码。

历史

无更改。

© . All rights reserved.