【问题标题】:System.Net.Http.HttpClient does not contain a definitions for DownloadDataSystem.Net.Http.HttpClient 不包含 DownloadData 的定义
【发布时间】:2014-01-13 13:59:07
【问题描述】:

我想使用 web api 获取歌词,但它有一个错误“System.Net.Http.HttpClient”不包含“DownloadData”的定义并且没有扩展方法“DownloadData”接受“System”类型的第一个参数可以找到 .Net.Http.HttpClient'(您是否缺少 using 指令或程序集引用?)

这是我的代码

internal static class LyricsFetcher
{
    internal static String GetLyrics(String Artist, String Title)
    {
        byte[] responseData;

        string URL;

        URL = "http://api.metrolyrics.com/v1/search/lyrics/?find=" + Artist + "%20" + Title + "&X-API-KEY=1234567890123456789012345678901234567890";

        HttpClient wClient = new HttpClient();
        responseData = wClient.DownloadData(URL); // error
        UTF8Encoding utf8 = new UTF8Encoding();
        String Lyrics = utf8.GetString(responseData,0,responseData.Length);
        return Lyrics;
    }
}

【问题讨论】:

  • 编译器错误(!)与您连接的站点有什么关系?

标签: c# dotnet-httpclient


【解决方案1】:

您应该使用 GetAsync 或 GetStreamAsync,而不是使用 DownloadData(在 HttpClient 中不可用)。 HttpClient 的优点是你可以使用异步方法,所以你应该继续使用它。作为奖励,它还可以在 PCL 中使用,因此最终您可以跨多个平台使用您的组件。

    internal static async Task<String> GetLyrics(String Artist, String Title)
    {
        byte[] responseData;

        string URL;

        URL = "http://api.metrolyrics.com/v1/search/lyrics/?find=" + Artist + "%20" + Title + "&X-API-KEY=1234567890123456789012345678901234567890";

        HttpClient wClient = new HttpClient();
        responseData = await wClient.GetByteArrayAsync(URL); // success!
        UTF8Encoding utf8 = new UTF8Encoding();
        String Lyrics = utf8.GetString(responseData, 0, responseData.Length);
        return Lyrics;
    }

【讨论】:

    【解决方案2】:

    HttpClient 没有DownloadData 方法。我相信你可能打算使用WebClient,它有一个DownloadData 方法。

    WebClient wClient = new WebClient();
    responseData = wClient.DownloadData(URL);
    

    【讨论】:

    • 如何使用 HttpClient 获取 responseData?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多