首页 > 解决方案 > 如何从 HTTP 请求中读取/输出响应

问题描述

我向网页发送 HTTP 请求以插入或检索数据。

这是我的代码:

string json = JsonConvert.SerializeObject(user);
using (var client = new HttpClient())
{
    var response =  client.PostAsync(
        "url",
         new StringContent(json, Encoding.UTF8, "application/json"));
}

DisplayAlert("Alert", json, "OK");
DisplayAlert("test", response, "test");

对于这个特定的例子;该网站应返回真或假。

但我想读取响应变量。

节目DisplayAlert("test", response, "test");错误。这是因为我试图阅读范围之外的响应。

我的问题是如何读取页面上的响应变量或输出响应变量?

编辑

{
    LoginModel user = new LoginModel();
    {
        user.email = email.Text;
        user.password = password.Text;

    };

    string json = JsonConvert.SerializeObject(user);

    using (var client = new HttpClient())
    {


    }

    var response = client.PostAsync(
        "https://scs.agsigns.co.uk/tasks/photoapi/login-photoapi/login-check.php",
         new StringContent(json, Encoding.UTF8, "application/json"));


    DisplayAlert("Alert", json, "OK");
     DisplayAlert("test", response, "test");

}

标签: c#http

解决方案


这会给您一个错误,因为您尝试访问在不同范围内声明的变量。如果将变量移到response“方法范围”内,错误将消失:

string json = JsonConvert.SerializeObject(user);

HttpResponseMessage response;
using (var client = new HttpClient())
{
    response = await client.PostAsync(
        "url",
         new StringContent(json, Encoding.UTF8, "application/json"));
}

DisplayAlert("Alert", json, "OK");
DisplayAlert("test", await response.Content.ReadAsStringAsync(), "test");

请注意await我之前添加的内容(您将在文档client.PostAsync()中找到有关 async/await 的更多信息)。

要获取响应内容的字符串表示,您可以使用以下方法:

await response.Content.ReadAsStringAsync(); 

这会将响应内容读取为字符串。


推荐阅读