简体   繁体   English

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

[英]How to send JSON GET data with an HTTP request in C#

So I am having a lot of trouble with how to send the below JSON data in C# format.所以我在如何以 C# 格式发送以下 JSON 数据方面遇到了很多麻烦。 I know exactly how to do it in cURL, but I can't figure this out for the life of me.我确切地知道如何在 cURL 中做到这一点,但我一生都无法弄清楚这一点。 This request is essential to what I am doing and I really need to get it done.这个请求对我正在做的事情至关重要,我真的需要完成它。 Here is the curl statement:这是 curl 语句:

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

If it helps at all I am making a request to an Elasticsearch server, and I am grabbing the JSON data.如果它有帮助,我正在向 Elasticsearch 服务器发出请求,并且我正在获取 JSON 数据。 This cURL request gives me EXACTLY what I need.这个 cURL 请求正是我所需要的。 Here is the C# code that I have now, but I am not sure how to add this JSON data to the GET request.这是我现在拥有的 C# 代码,但我不确定如何将此 JSON 数据添加到 GET 请求。 This is also gonna be running in the Unity game engine.这也将在 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();

The above is just from the documentation page, and I am pretty new to HTTP requests in code, so any help would be greatly appreciated.以上仅来自文档页面,我对代码中的 HTTP 请求非常陌生,因此将不胜感激。

I figured it out!我想到了!

    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();

The Query string is the JSON data in the original post.查询字符串是原始帖子中的 JSON 数据。 For those who want to know for the ELK stack, this will give you the JSON data(in string format) from the most recent event.对于那些想了解 ELK 堆栈的人,这将为您提供最近事件的 JSON 数据(字符串格式)。 Depending on what beat you use, this could be pretty cool for data visualization.根据您使用的节拍,这对于数据可视化可能非常酷。

Here's how I'd send a Unity WWW -request with POST:以下是我如何使用 POST 发送 Unity WWW请求:

    public IEnumerator SendSomething()
    {
        WWWForm wwwForm = new WWWForm();
        wwwForm.AddField("Parameter_Name", jsonString);

        WWW www = new WWW(url, wwwForm);
        yield return www;

        if (www.error == null)
        {
             Debug.Log("Everything worked!");
        }
        else
        {
             Debug.Log("Something went wrong: " + www.error);
        }
    }

The WWW-class defaults to GET if you don't supply the postData parameter (my wwwForm), so if you want to use GET you could just supply the WWW-class with:如果您不提供 postData 参数(我的 wwwForm),则 WWW 类默认为 GET,因此如果您想使用 GET,您可以只提供 WWW 类:

WWW www = new WWW(url + "?" + jsonString);

and skipping the first 2 rows of my method.并跳过我的方法的前两行。

Here we're utilizing the IEnumerator to yield return www: which waits for the request to complete until continuing.在这里,我们使用 IEnumerator 来yield return www:等待请求完成直到继续。 To utilize the IEnumerator method you invoke it with StartCoroutine(SendSomething());要使用 IEnumerator 方法,您可以使用StartCoroutine(SendSomething());调用它StartCoroutine(SendSomething()); which will run asyncronized.这将异步运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM