public async void GetWeatherInfo(CityName city)
{
var httpClient = new HttpClient();
var json = JsonConvert.SerializeObject(city);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var uri = new Uri(string.Format("http://api.openweathermap.org/data/2.5/weather?q={0}&appid=29d06aa8c8b3a8341ab876b124d7c&units=metric",json));
var result = await httpClient.GetAsync(uri);
if (result.IsSuccessStatusCode)
{
try
{
var weatherInfo = JsonConvert.DeserializeObject<WeatherInfo>(**result**);
}}}
我正在开发一个天气应用程序项目,并且试图从用户那里获取一个字符串城市名称。我将城市名称绑定到url并编写了GetRequest,但是在代码末尾出现“ 结果”错误。它应该反序列化响应,以便我可以更改响应并使用它。错误消息是:无法从'System.Net.Http.HttpResponseMessage'转换为'string'
答案 0 :(得分:1)
HttpClient.getAsync()
方法返回一个Task<HttpResponseMessage>
,其中还包括状态码和有关响应本身的更多信息。
返回任务{HttpResponseMessage}
代表异步操作的任务对象。
您需要从结果中提取内容。
尝试一下
public async void GetWeatherInfo(CityName city)
{
var httpClient = new HttpClient();
var json = JsonConvert.SerializeObject(city);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var uri = new Uri(string.Format("http://api.openweathermap.org/data/2.5/weather?q={0}&appid=29d06aa8c8b3a8341ab876b124d7c&units=metric",json));
var result = await httpClient.GetAsync(uri);
if (result.IsSuccessStatusCode)
{
try
{
string content = await result.Content.ReadAsStringAsync();
var weatherInfo = JsonConvert.DeserializeObject<WeatherInfo>(content);
}}}