如何使用HttpClient读取XML响应?

时间:2013-11-12 23:55:52

标签: c# httpclient

显然HttpClient是新建议的HTTP请求方式,因此我尝试使用它向Delicious API发出请求,返回XML响应。这就是我所拥有的:

internal class Program
{
    private static void Main(string[] args)
    {
        var credentials = new NetworkCredential("username", "password");
        var handler = new HttpClientHandler { Credentials = credentials};
        var client = new HttpClient(handler);

        var suggest = new Uri("https://api.del.icio.us/v1/posts/suggest");

        var suggestions =
            client.GetAsync(suggest.AddQueryParams("url", "https://yahoo.com"))
                .ContinueWith(t => t.Result.Content.ReadAsAsync<DeliciousSuggest>())
                .Unwrap()
                .Result;



        Console.ReadLine();
    }
}

public class DeliciousSuggest
{
    public string[] Popular { get; set; }
    public string[] Recommended { get; set; }
    public string[] Network { get; set; }
}

但是,它会在ReadAsAsync

上抛出异常
  

其他信息:无法加载文件或程序集“Newtonsoft.Json,Version = 4.5.0.0,Culture = neutral,PublicKeyToken = 30ad4fe6b2a6aeed”或其中一个依赖项。系统找不到指定的文件。

也许我错过了一些集会,但这让我感到震惊。返回类型是XML,而不是JSON,但我仍然不太确定这个ReadAsAsync方法是如何工作的,或者我如何指定它。

示例响应如下所示:

<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<suggest>
<popular>yahoo!</popular>
<popular>yahoo</popular>
<popular>web</popular>
<popular>tools</popular>
<popular>searchengines</popular>
<recommended>yahoo!</recommended>
<recommended>yahoo</recommended>
<recommended>web</recommended>
<network>for:Bernard</network>
<network>for:britta</network>
<network>for:deusx</network>
</suggest>

如何将其解析为某种可用的格式?

1 个答案:

答案 0 :(得分:15)

&#34;我如何将其解析成一些可用的格式?&#34;

    [XmlRoot("suggest")]
public class DeliciousSuggest {
    [XmlElement("popular")]
    public string[] Popular { get; set; }

    [XmlElement("recommended")]
    public string[] Recommended { get; set; }

    [XmlElement("network")]
    public string[] Network { get; set; }
}

并使用XmlSerializer反序列化。


您应该将del.icio.us的响应作为字符串读回来,然后您可以按如下方式对其进行反序列化:

var s = "this is the response from del"; 
var buffer = Encoding.UTF8.GetBytes(s); 
using (var stream = new MemoryStream(buffer)) { 
    var serializer = new XmlSerializer(typeof(DeliciousSuggest)); 
    var deliciousSuggest = (DeliciousSuggest)serializer.Deserialize(stream); 
    //then do whatever you want
}