gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:18:39 25 4
gpt4 key购买 nike

我有这个代码:

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

它的内容在哪里?

编辑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);

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com