简体   繁体   中英

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. 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:

   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.

        // 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.

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.

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

    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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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