基本格式:
HttpClient client = new HttpClient(); Uri uri = new Uri(url); HttpResponseMessage response = await client.GetAsync(uri); response.EnsureSuccessStatusCode(); string str = await response.Content.ReadAsStringAsync();
若得到Json数据:
可以通过以下方法方便的转换到类中:
var jsonMessage = await response.Content.ReadAsStringAsync();
var serializer = new DataContractJsonSerializer(typeof(JsonClass));//在json2csharp中转换过来的类
var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonMessage));
var result = (JsonClass)serializer.ReadObject(ms);
若得到Xml数据:
可以通过遍历节点将数据一个个手动存放到类中:
string xml = await response.Content.ReadAsStringAsync();
if (xml != null)
{
List<CNBlog> list_blogs = new List<CNBlog>();
CNBlog cnblog;
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNode feed = doc.ChildNodes[1];
foreach (XmlNode node in feed.ChildNodes)
{
if (node.Name.Equals("entry"))
{
cnblog = new CNBlog();
foreach (XmlNode node2 in node.ChildNodes)
{
if (node2.Name.Equals("id"))
{
cnblog.ID = node2.InnerText;
}
if (node2.Name.Equals("title"))
{
cnblog.Title = node2.InnerText;
}
if (node2.Name.Equals("summary"))
{
cnblog.Summary = node2.InnerText + "...";
}
}
list_blogs.Add(cnblog);
}
}
}
XML的数据如下:
<?xml version="1.0" encoding="utf-8" ?> - <feed xmlns="http://www.w3.org/2005/Atom"> <title type="text">博客园</title> <id>uuid:09b99565-46b8-4767-ad8d-ea0283b7b1ac;id=41476</id> <updated>2016-05-22T03:01:05Z</updated> <link href="http://www.cnblogs.com/" /> - <entry>//一段的入口 <id>5516348</id> <title type="text">教你如何剖析源码</title> <summary type="text">有近千行代码。看着都崩溃了。。。</summary> <published>2016-05-22T11:00:00+08:00</published> <updated>2016-05-22T03:01:05Z</updated> - <author> <name>狼行博客园</name> <uri>http://www.cnblogs.com/lang5230/</uri> <avatar>http://pic.cnblogs.com/face/835234/20151119122152.png</avatar> </author> <link rel="alternate" href="http://www.cnblogs.com/lang5230/p/5516348.html" /> <blogapp>lang5230</blogapp> <diggs>0</diggs> <views>1</views> <comments>0</comments> </entry>