我想使用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;
}
}
答案 0 :(得分:3)
您应该使用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;
}
答案 1 :(得分:1)
HttpClient
没有DownloadData
方法。我相信您可能打算使用WebClient
,DownloadData
方法。
WebClient wClient = new WebClient();
responseData = wClient.DownloadData(URL);