gpt4 book ai didi

http - 将 HttpResponseMessage 转换为对象

转载 作者:可可西里 更新时间:2023-11-01 16:27:53 29 4
gpt4 key购买 nike

我有这个结构,我也在使用 System.Net.HttpNewtonsoft。我需要接收 web 服务响应并在我的类(class)中将其转换,但我不知道如何使用 HttpResponseMessage 来做到这一点,而且我已经变红的帖子对我没有帮助。这是一个 Xamarin.forms 项目。

 public static async Task<User> PostLoginAsync(string login, string senha)
{
using (var client = new HttpClient())
{
try
{
login = "email@hotmail.com";
senha = "1111111";

var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("id", "1200"),
new KeyValuePair<string, string>("email", login),
new KeyValuePair<string, string>("password", senha),
new KeyValuePair<string, string>("json", "1"),
});

HttpResponseMessage response = await client.PostAsync("http://ws.site.com", content);

return null;
}

catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return null;
}
}
}

我的类(class):

class User
{
public string codigo { get; set; }
public string nome { get; set; }
public string email { get; set; }
public string senha { get; set; }
public string imagem { get; set; }
public DateTime dataDeNasc { get; set;}
public string cidade { get; set; }
public string estado { get; set; }
public string telefone { get; set; }
public string sexo { get; set; }
}

如果您能帮助我...我将不胜感激。还是谢谢你

最佳答案

您需要等待来自 HttpResponseMessage 的内容。

public static async Task<User> PostLoginAsync(string login, string senha)
{
using (var client = new HttpClient())
{
try
{
login = "email@hotmail.com";
senha = "1111111";

var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("id", "1200"),
new KeyValuePair<string, string>("email", login),
new KeyValuePair<string, string>("password", senha),
new KeyValuePair<string, string>("json", "1"),
});

HttpResponseMessage response = await client.PostAsync("http://ws.site.com", content);

var responseContent = await response.Content.ReadAsStringAsync();
var user = JsonConvert.DeserializeObject<User>(responseContent);

return user;
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return null;
}
}
}

关于http - 将 HttpResponseMessage 转换为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45550761/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com