首页 > 解决方案 > 对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@", lat.ToString());
        url = url.Replace("@lon@", 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;
    }


}

标签: c#visual-studiowcfsoapasmx

解决方案


推荐阅读