我有以下代码:

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,以便检查其是否已正确初始化?

c# - 使用httpClient发布json尚未到达服务器-LMLPHP

它的内容在哪里?

编辑1

我检查了服务器,并得到以下数据:

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”时,连接是关闭的,但是当我发布到我的服务器时,该连接是保持活动的,有什么区别?是否有可能我没有从服务器上的客户端读取所有数据,而应该等待另一个数据包?

最佳答案

我没有信誉对您的帖子发表评论(这是我想发表此评论的位置-因此,请就拒绝投票对我说几句轻松)。但是,我们今天遇到的问题几乎与您一样。在与同事协商之后,我们实际上可以通过更改行来获取JSON响应:

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




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


那揭示了我们的JSON

关于c# - 使用httpClient发布json尚未到达服务器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48524297/

10-11 22:26
查看更多