2013-02-10 82 views
0

我剛剛開始在C#中使用一些API。在我的表格中,我添加了一個服務參考http://wsf.cdyne.com/WeatherWS/Weather.asmx。一切都很好,我可以利用它的圖書館。現在我試圖使用例如http://free.worldweatheronline.com/feed/apiusage.ashx?key=(key在這裏進行)& format = xml。 [我有一把鑰匙]現在,當我嘗試將它用作服務參考時,我無法使用它。在C#中使用Web服務#

我必須在表單中調用它而不是引用它嗎?或做某種轉換?如果它的xml或json類型也是否重要?

回答

1

ASMX是舊技術,並在引擎蓋下使用SOAP。 SOAP不傾向於使用查詢字符串參數,它將參數作爲消息的一部分。

ASHX是不同的東西(可能是任何東西,它是用.NET編寫原始HTML/XML頁面的一種方法),所以你不能將調用一個的方法轉移到另一個。它也沒有服務引用,它可能是通過原始HTTP請求請求的。您需要熟悉服務文檔以發現如何使用它。

+1

注意,這個問題是不是ASMX與ASHX。它是隨機的,而不是SOAP。 – 2013-02-10 18:07:40

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