c# - 如何从 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");
}
解决方案
这会给您一个错误,因为您尝试访问在不同范围内声明的变量。如果将变量移到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();
这会将响应内容读取为字符串。
推荐阅读
- google-translate - Google Translate API 会忽略重音字符
- flutter - 颤振:如果在列表类上
- python - 保存后如何组合matplotlib图形?
- uitabbarcontroller - 如何正确呈现标签栏?对 tabbarcontroltest.ViewController 的开始/结束外观转换的不平衡调用:
- opencv - 流与 OpenCV 不同步
- javascript - 使用 jQuery 上传带有数据的文件
- javascript - 在传单地图上显示 json 数据
- java - 外部进程能否强制 JVM 抛出“java.lang.OutOfMemoryError:GC 开销限制超出”
- continuous-integration - 本地地形开发:计划但不适用?
- javascript - 如何使用 React 获取局域网中的计算机名称和本地 IP 地址