简体   繁体   English

C#和Forecast API

[英]C# and Forecast API

I am completely new to API data retreival, and would appreciate some help. 我对API数据转发完全不熟悉,并希望得到一些帮助。 This is the code I have at the moment: 这是我目前的代码:

else if (e.KeyCode == Keys.Enter & InputTextbox.Text.Contains("hot"))
{
    try
    {
        XElement doc = XElement.Load("https://api.forecast.io/forecast/*APIKEY*/-31.4296,152.9082");
        OutputTextbox.Text = "It is currently " + doc;                                                             
        pBuilder.ClearContent();                                                                                        
        pBuilder.AppendText(OutputTextbox.Text);                                                                        
        sSynth.Speak
        pBuilder);                                                                                                             
        e.SuppressKeyPress = true;                                                                                                          
        InputTextbox.Text = "";
    }
    catch (System.Xml.XmlException fe)
    {
        MessageBox.Show(fe.Message);
    }

This gives back the error message: "Data at the root level is invalid. Line 1, position 1." 这会返回错误消息:“根级别的数据无效。第1行,位置1”。

Can someone please let me know where I am going wrong? 有人可以让我知道我哪里出错吗?

First, you need to see what the output of the api call is, try: 首先,你需要看看api调用的输出是什么,试试:

using(var client = new WebClient()) {
    var responseStr = client.DownloadString("https://api.forecast.io/forecast/*APIKEY*/-31.4296,152.9082");
    OutputTextbox.Text = responseStr;
}

Then, to load this xml with XElement, it needs to be completely valid XML. 然后,要使用XElement加载此xml,它需要是完全有效的XML。 That's the source of your error message: XElement is very strict. 这是您的错误消息的来源:XElement非常严格。 If the response is HTML, consider using HtmlAgilityPack , it will save your sanity. 如果响应是HTML,请考虑使用HtmlAgilityPack ,它将保存您的理智。

var doc = new HtmlDocument();
doc.Load("https://....");

If it's a json api or something like that, consider using ServiceStack . 如果它是json api或类似的东西,请考虑使用ServiceStack That will also save your sanity. 这也将拯救你的理智。

Good luck. 祝好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM