2017-10-16 73 views
-1

我有这个hardware来自Patlite, 这个硬件有一个HTTP命令控制功能,例如,如果我复制网址“http://192.168.10.1/api/control?alert=101002”在我的电脑中镀铬,它将根据需要激活硬件。c#如何发送HTTP命令,因为这 - http://192.168.10.1/api/control?alert=101002

我想从我的代码发送命令。

我想这个代码没有运气:

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

有从手动图片:enter image description here

感谢

+0

“我试过这段代码没有运气”发生了什么事? – Oscar

回答

0
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; 
      } 
     } 

这样的代码使用url “http://192.168.10.1/api/control?alert=101002” 送得到request.Good运气!

+0

非常感谢,所以我只需要打开它作为WebClient作为Chrome? –

+0

@ Eran.G是的,效果是一样的。 –

1

您需要为此创建一个WebRequest实例。

WebRequest request = WebRequest.Create("http://192.168.10.1/api/control?alert=101002"); 
WebResponse response = request.GetResponse(); 

您可能需要将某些属性设置为请求方法和凭据才能使其工作。

看到这个:

https://msdn.microsoft.com/en-us/library/456dfw4f(v=vs.100).aspx

+0

当你回答我时,我只是编辑答案,添加我所尝试的。 –

+0

@ Eran.G但是你不会说你在代码中犯的错误。发生了什么? – Oscar

+0

正如你所看到的,W.Ym帮助我,因为它很清楚,请从我的问题中删除-1。 –