c# - 对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;
}
}
解决方案
推荐阅读
- service - 服务启动 gunicorn 失败并显示“启动请求重复太快”
- azure-databricks - 使用 Hyperopt 禁用自动记录标签到 MLflow
- ios - 如何将 json 解码为 Codable 以在 SwiftUI 预览中使用?
- sql - 使用 SSIS 表达式将全名分解为单独的字段,最后一个中间
- javascript - 如何在队列中播放音频 TTS?
- kdb - 如何在 KDB Q 中解析日期时间?
- javascript - 如何将“ex.Message”生成的字符串值从我的 C# 函数传递给我的 Javascript 函数 Sweet Alert,以显示错误消息
- django - Django 过滤器也可以获取反向外键,或者更好的方法来组合相关的数据库信息?
- weka - Weka 属性选择的部分结果
- sql - 根据另一列的值按分号将列值拆分为单独的行