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

时间:2022-08-22 17:50:24

So I am having a lot of trouble with how to send the below JSON data in C# format. I know exactly how to do it in cURL, but I can't figure this out for the life of me. This request is essential to what I am doing and I really need to get it done. Here is the curl statement:

因此,我在如何以c#格式发送下面的JSON数据上遇到了很多麻烦。我知道怎么用卷发来做,但我怎么也弄不清楚。这个要求对于我正在做的事情是必不可少的,我真的需要把它完成。下面是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. This cURL request gives me EXACTLY what I need. Here is the C# code that I have now, but I am not sure how to add this JSON data to the GET request. This is also gonna be running in the Unity game engine.

如果它能帮助我,我正在向一个弹性搜索服务器发出请求,我正在抓取JSON数据。这个卷曲的请求正好给了我我所需要的。这里是我现在拥有的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();

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请求非常陌生,所以非常感谢您的帮助。

2 个解决方案

#1


1  

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. 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. Depending on what beat you use, this could be pretty cool for data visualization.

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

#2


0  

Here's how I'd send a Unity WWW-request with POST:

下面是我如何用POST发送一个Unity WWW-request:

    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-class默认为获取,因此如果您想使用GET,可以向WWW-class提供:

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. To utilize the IEnumerator method you invoke it with StartCoroutine(SendSomething()); which will run asyncronized.

在这里,我们使用IEnumerator来返回www:它等待请求完成,直到继续。要使用IEnumerator方法,可以使用StartCoroutine(SendSomething())调用它;这将asyncronized运行。

#1


1  

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. 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. Depending on what beat you use, this could be pretty cool for data visualization.

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

#2


0  

Here's how I'd send a Unity WWW-request with POST:

下面是我如何用POST发送一个Unity WWW-request:

    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-class默认为获取,因此如果您想使用GET,可以向WWW-class提供:

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. To utilize the IEnumerator method you invoke it with StartCoroutine(SendSomething()); which will run asyncronized.

在这里,我们使用IEnumerator来返回www:它等待请求完成,直到继续。要使用IEnumerator方法,可以使用StartCoroutine(SendSomething())调用它;这将asyncronized运行。