使用C#中的web服务

本文关键字:服务 web 中的 使用 | 更新日期: 2023-09-27 17:58:39

我刚开始在C#中玩一些API。在我的表格中,我添加了一个服务参考http://wsf.cdyne.com/WeatherWS/Weather.asmx.一切都很好,我可以利用它的图书馆。现在我试着用http://free.worldweatheronline.com/feed/apiusage.ashx?key=(键在这里)&format=xml。[我有一把钥匙]现在,当我试图将其用作服务参考时,我无法使用。

我必须在我的表单中调用它而不是引用它吗?或者做某种转换?它的xml或json类型也有关系吗?

使用C#中的web服务

ASMX是一项古老的技术,它在后台使用SOAP。SOAP不倾向于使用查询字符串参数,它将参数作为消息的一部分。

ASHX是不同的(它可以是任何东西,它是在.NET中编写原始HTML/XML页面的一种方法),所以不能将调用其中一个的方法转移到另一个。它也没有服务引用,很可能是通过原始HTTP请求来请求的。您需要查看服务文档以了解如何使用它。

worldweatheronline不返回WebService客户端可使用的SOAP-XML。因此,您应该像使用许多REST服务一样下载响应并解析它。

string url = "http://free.worldweatheronline.com/feed/apiusage.ashx?key=" + apikey;
using (WebClient wc = new WebClient())
{
    string xml = wc.DownloadString(url);
    var xDoc = XDocument.Parse(xml);
    var result = xDoc.Descendants("usage")
                    .Select(u => new
                    {
                        Date = u.Element("date").Value,
                        DailyRequest = u.Element("daily_request").Value,
                        RequestPerHour = u.Element("request_per_hour").Value,
                    })
                    .ToList();
}

它的xml或json类型也有关系吗

不,最后您必须自己解析响应。

string url = "http://free.worldweatheronline.com/feed/apiusage.ashx?format=json&key=" + apikey;
using (WebClient wc = new WebClient())
{
    string json = wc.DownloadString(url);
    dynamic dynObj = JsonConvert.DeserializeObject(json);
    var jArr  = (JArray)dynObj.data.api_usage[0].usage;
    var result = jArr.Select(u => new
                     {
                         Date = (string)u["date"],
                         DailyRequest = (string)u["daily_request"],
                         RequestPerHour = (string)u["request_per_hour"]
                     })
                    .ToList();
}

PS:我使用Json.Net来解析Json字符串