繁体   English   中英

如何从HTTP请求读取/输出响应

[英]How to read/output response from the HTTP request

我将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");

对于这个特定的例子; 网站应返回true或false。

但是我想阅读响应变量。

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");

}

这会给您带来错误,因为您尝试访问在其他作用域内声明的变量。 如果将变量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");

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

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

await response.Content.ReadAsStringAsync(); 

这将以字符串形式读取响应内容。

string json = JsonConvert.SerializeObject(user);
HttpResponseMessage response;
using (var client = new HttpClient())
{
    response = client.PostAsync(
        "url",
         new StringContent(json, Encoding.UTF8, "application/json").Result);
}
var body = response.Content.ReadAsStringAsync().Result;
DisplayAlert("Alert", json, "OK");
DisplayAlert("test", body, "test");

应该通过将变量的声明移到范围之外,并在调用内部更新值来工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM