我有这个结构,我也在使用 System.Net.Http Newtonsoft
我需要接收Web服务响应并将其转换为我的类(class),但我不知道如何使用HttpResponseMessage进行响应,而我发的红色帖子对我没有帮助。
这是一个Xamarin.forms项目。

 public static async Task<User> PostLoginAsync(string login, string senha)
    {
        using (var client = new HttpClient())
        {
            try
            {
                login = "[email protected]";
                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 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 protected]";
            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/

10-15 05:34