Search code examples
c#asp.netposthttpwebrequestwebrequest

c# How to send HTTP command as this - http://192.168.10.1/api/control?alert=101002


I have this hardware from Patlite, This hardware has an HTTP command control function, for example, if I copy the url "http://192.168.10.1/api/control?alert=101002" to chrome in my computer, it will activate the hardware as needed.

I want to send the command from my code.

I tried this code with no luck:

System.Net.ServicePointManager.Expect100Continue = false;
        WebRequest request = WebRequest.Create("http://10.0.22.222/api/control");
        request.Method = "post";
        request.ContentType = "application/x-www-form-urlencoded";
        string postData = "alert=101002";
        byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        request.ContentLength = byteArray.Length;
        // Get the request stream.
        Stream dataStream = request.GetRequestStream();

        // Write the data to the request stream.
        dataStream.Write(byteArray, 0, byteArray.Length);

        // Close the Stream object.
        dataStream.Close();
        WebResponse response = request.GetResponse();

There is a picture from the manual:enter image description here

Thanks


Solution

  • public static string Get(string url, Encoding encoding)
            {
                try
                {
                    var wc = new WebClient { Encoding = encoding };
                    var readStream = wc.OpenRead(url);
                    using (var sr = new StreamReader(readStream, encoding))
                    {
                        var result = sr.ReadToEnd();
                        return result;
                    }
                }
                catch (Exception e)
                {
                    //throw e;
                    return e.Message;
                }
            }
    

    like this code use the url "http://192.168.10.1/api/control?alert=101002" to send get request.Good luck!