0

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

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

4

2 回答 2

1

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

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

于 2013-02-10T18:01:30.630 回答
0

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字符串

于 2013-02-10T21:20:42.040 回答