对soap服务中的外部api的异步请求

问题描述

我正在尝试编写一个肥皂服务,它根据某个位置的纬度和经度返回小麦。我想使用异步 httpclient 从外部 openweathermap api 请求数据。

调试这段代码时,进程突然停止在这行getResponse函数的开头:

string responseBody = await client.GetStringAsync(url);

即使没有肥皂包装器,输出也是一个空的 xml 对象。

using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Services;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://cloud4090.weatherProvider.be/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script,using ASP.NET AJAX,uncomment the following line. 
// [System.Web.Script.Services.ScriptService]
public class WeatherProvider : System.Web.Services.WebService
{

    private const string API_KEY = "80b7844b635e86689430677c077b3ef2";
    private const string Url_weather_forecast = "http://api.openweathermap.org/data/2.5/forecast?" + "lat=@lat@&lon=@lon@&units=metric&appid=" + API_KEY;
    private const string Url_current_weather = "http://api.openweathermap.org/data/2.5/weather?" + "lat=@lat@&lon=@lon@&units=metric&appid=" + API_KEY;

    static readonly HttpClient client = new HttpClient();

    public WeatherProvider()
    {
        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }


    [WebMethod]
    public async Task<string> getWeatherCurrentAsync(float lat,float lon)
    {
        string url = Url_current_weather.Replace("@lat@",lat.ToString());
        url = url.Replace("@lon@",lon.ToString());

        string response = await getResponse(url);

        return response;
    }

    [WebMethod]
    public async Task<string> getWeatherForecastAsync(float lat,float lon)
    {
        string url = Url_weather_forecast.Replace("@lat@",lon.ToString());

        string response = await getResponse(url);

        return response;
    }


    static async Task<string> getResponse(string url)
    {
        // Call asynchronous network methods in a try/catch block to handle exceptions.
        try
        {
            string responseBody = await client.GetStringAsync(url);
            Console.WriteLine(responseBody);
            return responseBody;
        }
        catch (HttpRequestException e)
        {
            Console.WriteLine("\nException Caught!");
            Console.WriteLine("Message :{0} ",e.Message);
        }
        return null;
    }


}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)