gpt4 book ai didi

c# - 如何在 C# 中使用 HTTP 请求发送 JSON GET 数据

转载 作者:行者123 更新时间:2023-11-30 23:16:42 25 4
gpt4 key购买 nike

所以我在如何以 C# 格式发送以下 JSON 数据方面遇到了很多麻烦。我确切地知道如何在 cURL 中执行此操作,但我终生无法弄清楚这一点。这个请求对我正在做的事情至关重要,我真的需要完成它。这是 curl 语句:

   curl <ip of server>/<index>/_search?pretty=true -d '
{
"query": {
"match_all": {}
},
"size": 1,
"sort": [{
"_timestamp": {
"order": "desc"
}
}]
}

如果有帮助的话,我正在向 Elasticsearch 服务器发出请求,然后获取 JSON 数据。这个 cURL 请求完全符合我的需要。这是我现在拥有的 C# 代码,但我不确定如何将此 JSON 数据添加到 GET 请求中。这也将在 Unity 游戏引擎中运行。

        // Create a request for the URL.        
request = WebRequest.Create(elk_url);
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.

response = (HttpWebResponse)request.GetResponse();
// Display the status.
Debug.Log(response.StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Debug.Log(responseFromServer);
// Cleanup the streams and the response.
reader.Close();
dataStream.Close();
response.Close();

以上仅来自文档页面,我对代码中的 HTTP 请求还很陌生,因此非常感谢任何帮助。

最佳答案

我想通了!

    WebRequest request = WebRequest.Create(elk_url);

request.ContentType = "application/json";
request.Method = "POST";
byte[] buffer = Encoding.GetEncoding("UTF-8").GetBytes(queryString);
string result = System.Convert.ToBase64String(buffer);
Stream reqstr = request.GetRequestStream();
reqstr.Write(buffer, 0, buffer.Length);
reqstr.Close();

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Debug.Log(response.StatusDescription);
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Debug.Log(responseFromServer);
// Cleanup the streams and the response.
reader.Close();
dataStream.Close();
response.Close();

查询字符串是原始帖子中的 JSON 数据。对于那些想了解 ELK 堆栈的人,这将为您提供最近事件的 JSON 数据(字符串格式)。根据您使用的节拍,这对于数据可视化来说可能非常酷。

关于c# - 如何在 C# 中使用 HTTP 请求发送 JSON GET 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41896996/

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