c# - 在 Http 响应消息中查找 POST 的结果
问题描述
我正在使用 VS2017 中的 Windows 窗体应用程序构建 REST 客户端(c#)。我已经能够使用 HttpClient.PostAsJsonAsync() 和 ReadAsync() 方法成功地从服务器获取和发布请求。我正在尝试将一些数据发布到服务器,并且在成功 POST 后,服务器会响应一个唯一的字符串,例如“1c77ad2e-54e0-4187-aa9d-9a55286b1f7a”
我得到了 POST 的成功响应代码(200 - OK)。但是,我不确定在哪里检查结果字符串。我检查了 HttpResponseMessage.Content 的内容
static async Task<HttpStatusCode> PostBurstData(string path, BurstRequest
burstRequest)
{
HttpResponseMessage response = await client.PostAsJsonAsync(path, burstRequest);
response.EnsureSuccessStatusCode();
Console.WriteLine(response.Content.ToString());
// return response
return response.StatusCode;
}
发送到该函数调用的数据如下:
BurstRequest request = new BurstRequest();
request.NodeSerialNumbers = SubSerialList;
request.StartTime = ((DateTimeOffset)dateTimePicker1.Value).ToUnixTimeMilliseconds();
HttpStatusCode statusCode = new HttpStatusCode();
statusCode = await PostBurstData(post_burst_url, request);
我应该在哪里搜索服务器响应成功 POST 的字符串?是否应该使用 ReadAsync() 读取内容?
if (response.IsSuccessStatusCode)
{
var data = await response.Content.ReadAsAsync();
}
解决方案
为什么不尝试HttpContent
如下使用:
using (HttpResponseMessage response = await client.GetAsync(url)) // here you can use your own implementation i.e PostAsJsonAsync
{
using (HttpContent content = response.Content)
{
string responseFromServer = await content.ReadAsStringAsync();
}
}
推荐阅读
- javascript - 如何使用 Google Chart 更改图例中的背景颜色?
- java - 将 Jackson、@JsonIdentityInfo 和 @JsonDeserialize 与 lombok Builder 一起使用时出现 MismatchedInputException
- mysql - 谷歌SQL副本需要上传视图的程序和功能
- mysql - woocommerce 在 Wordpress 中重复执行 mysql
- android - RecyclerView match_parent 中带有 HorizontalScrollview 的自定义视图不起作用
- security - 单击装箱单时出现 AX 2012 访问被拒绝错误
- php - XMPP 客户端接收服务器消息
- c# - 使用 HttpClient 发送图像到 POST WebApi 并使用数据
- java - 这可以转换为流式单线吗?
- reactjs - 实现文章的正确方法及其在反应环境中的评论