使用httpClient发布json没有到达服务器

时间:2018-01-30 14:53:35

标签: c# json dotnet-httpclient httpcontent

我有这段代码:

String json = "{\"name\":\"listFiles\"}";

// Wrap our JSON inside a StringContent which then can be used by the HttpClient class
HttpContent httpContent = new StringContent(json, Encoding.UTF8, "application/json");

HttpResponseMessage response = client.PostAsync(endPoint, httpContent).Result;
response.EnsureSuccessStatusCode();

当这篇文章完成后,我可以看到该服务器收到了一个电话,但内容为空(内容大小正确,但没有数据)。

我试图调查httpContent是否有json数据,但我看不到任何数据。

为什么这段代码,将空白数据发布到服务器以及为什么我在httpContent中看不到任何数据?

如何从httpContent中提取json,以便检查它是否已正确初始化?

Value httpContent

它的内容在哪里?

EDIT1

我检查了服务器,我收到了这些数据:

POST /osc/command/execute HTTP/1.1
Content-Type: application/json
Accept: application/json, application/xml, text/json, text/x-json, text/javascript, text/xml
User-Agent: RestSharp/106.2.1.0
Host: 192.168.1.138
Content-Length: 32
Accept-Encoding: gzip, deflate
Connection: Keep-Alive

当我使用restshart库发送数据时如下:

var client = new RestClient("http://192.168.1.138/osc/command/execute");
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/json");
request.AddParameter("application/json", "{\n  \"name\":\"camera.listFiles\"\n}\n", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);

当我使用邮递员发布相同的代码时,我在服务器上得到了这个:

POST /osc/command/execute HTTP/1.1
cache-control: no-cache
Postman-Token: 83ecd3ec-a85d-41a6-ab0e-029ee1690cce
Content-Type: application/json
User-Agent: PostmanRuntime/6.3.2
Accept: */*
Host: 192.168.1.138
accept-encoding: gzip, deflate
content-length: 32
Connection: keep-alive

{
 "name":"camera.listFiles"
}

那么为什么在我发布的内容中,我在阅读数据包的最后没有任何内容?

编辑2

我将数据发布到“http://httpbin.org/post”,我得到的结果是:

{
 "args": {},
 "data": "{\"name\":\"listFiles\"}",
 "files": {},
 "form": {},
 "headers": {
   "Accept": "application/json",
   "Connection": "close",
   "Content-Length": "20",
   "Content-Type": "application/json; charset=utf-8",
   "Expect": "100-continue",
   "Host": "httpbin.org"
 },
 "json": {
   "name": "listFiles"
 },
 "origin": "91.240.174.154",
 "url": "http://httpbin.org/post"
}

我在这里看不到任何有效载荷,但我可以在其中看到带有我数据的json。问题是为什么没有本文档中解释的有效负载:How are parameters sent in an HTTP POST request?

备注1

我可以看到,当我发布到“http://httpbin.org/post”时,连接已关闭,但当我发布到我的服务器时,连接是保持活动状态,有什么区别?有没有可能我没有从服务器上的客户端读取所有数据,我应该等待另一个数据包?

1 个答案:

答案 0 :(得分:1)

我没有声明对你的帖子发表评论(这是我想发表评论的地方 - 所以请放轻松关于我的投票)。但是我们的问题几乎与你今天的问题完全相同。在与同事讨论之后,我们能够通过更改您的行来获得JSON响应:

HttpResponseMessage response = client.PostAsync(endPoint, httpContent).Result;

var response = client.PostAsync(endPoint, httpContent).Result.Content.ReadAsStringAsync();

揭示了我们的JSON