WCF HTTP 获取 api

WCF HTTP GET api

在我的 .NET 项目中,我必须使用 HTTP GET 请求从 API 获取我所在城市的天气信息。由于我的 JavaScript 背景,我认为 "OK, so all I need is something like app.get(url, body)",所以我从这样开始:

        using (var client = new WebClient())
        {
            var responseString = client.DownloadString("http://www.webservicex.net/globalweather.asmx/GetWeather?CityName=" + city + "&CountryName=" + country);
            string xmlString = DecodeXml(responseString);

            return xmlString;
        }

不幸的是,我不得不使用 WCF 来获取数据。我在网上搜索了一些教程,但我找不到任何关于从外部来源获取数据的内容,只是创建自己的 API。

我不是母语人士,所以也许我只是不知道如何寻找解决方案,但如果你能给我一些建议就太棒了。

假设您使用的是 Visual Studio。添加服务引用,然后在地址中键入“http://www.webservicex.net/globalweather.asmx”并点击“开始”。它会自动生成终点供您使用。

那么代码是这样的:

        ServiceReference1.GlobalWeatherSoapClient client = new ServiceReference1.GlobalWeatherSoapClient("GlobalWeatherSoap");
        string cities = client.GetCitiesByCountry("Hong Kong");

如果你只想使用 HTTP GET,你可以这样做:

var city = "Dublin";
var country = "Ireland";

WebRequest request = WebRequest.Create(
    "http://www.webservicex.net/globalweather.asmx/GetWeather?CityName=" + 
    city + 
    "&CountryName=" + country);

request.Credentials = CredentialCache.DefaultCredentials;

WebResponse response = request.GetResponse();

Console.WriteLine(((HttpWebResponse)response).StatusDescription);

Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();

Console.WriteLine(responseFromServer);

reader.Close();
response.Close();
Console.ReadLine();

请注意,我没有HTML解码这里的响应,你可以简单地使用HttpUtility.HtmlDecode。

此外,您还需要包含以下 using 语句:

using System.IO;
using System.Net;