0

我有一个通过以太网连接到静态 IP 上的设备。有一个与设备通信的html接口。接口监控设备的io。它具有更改 IP 地址、子网掩码、MAC 地址和默认网关等内容的配置设置。这也是您向设备发送命令的方式。

我想制作一个 C# Windows 窗体来仅代表我需要的功能。我被赶上的地方是从表单发送命令。

html 接口使用 jquery 将命令发送回设备。

function sendCMD(indata) {$.post("setcmd.cgx", indata, function (data) {});

sendCMD({ver : "1",cmd : "abf"});

我目前正在尝试通过 WebRequest 将帖子发回,它只是返回 URI 的 html。我得出的结论是,我不应该为此使用 WebRequest 和/或我发送的帖子数据不正确。

我目前拥有的:

private void btnAimingBeamOn_Click(object sender, EventArgs e)
    {
        string postData = "\"setcmd.cgx\", {\n\rver : \"1\", \n\rcmd : \"abn\"\n\r}, function (data) {}";
        byte[] byteArray = Encoding.UTF8.GetBytes(

        Uri target = new Uri("http://192.168.3.230/index.htm"); 
        WebRequest request = WebRequest.Create(target);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = byteArray.Length;

        Stream dataStream = request.GetRequestStream();
        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();

        WebResponse response = request.GetResponse();
        txtABNStatus.Text = (((HttpWebResponse)response).StatusDescription);

        dataStream = response.GetResponseStream();
        StreamReader reader = new StreamReader(dataStream);
        string responseFromServer = reader.ReadToEnd();
        txtABNResponse.Text = (responseFromServer);

        reader.Close();
        response.Close();
        dataStream.Close();
    }

任何有关发送帖子的正确方法以及如何格式化帖子数据的帮助将不胜感激。

4

3 回答 3

4

您需要将数据发布到“setcmd.cgx”,而不是将其添加到您发布的数据中。

// You need to post the data as key value pairs:
string postData = "ver=1&cmd=abf";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);

// Post the data to the right place.
Uri target = new Uri("http://192.168.3.230/setcmd.cgx"); 
WebRequest request = WebRequest.Create(target);

request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;

using (var dataStream = request.GetRequestStream())
{
    dataStream.Write(byteArray, 0, byteArray.Length);
}

using (var response = (HttpWebResponse)request.GetResponse())
{
   //Do what you need to do with the response.
}
于 2013-06-04T15:51:11.503 回答
0

您应该在 Fiddler 之类的调试器中查看请求,并将真实站点与您的代码发送的请求进行比较。上面代码片段中的一个可疑之处是您以 JSON 格式发送数据,但声称它是“application/x-www-form-urlencoded”而不是“application/json”。

您可能还需要设置诸如 User-Agent 之类的标头和/或 cookie 或身份验证标头。

于 2013-06-04T15:39:20.533 回答
0

如果您不需要多线程 webclient 将完成这项工作。

 string data = "\"setcmd.cgx\", {\n\rver : \"1\", \n\rcmd : \"abn\"\n\r}, function (data) {}";
    WebClient client = new WebClient();
    client.Encoding = System.Text.Encoding.UTF8;

    string reply = client.UploadString("http://192.168.3.230/index.htm", data);
    //reply contains the web responce

另外,如果您使用的是 winforms(看起来您是),您应该考虑使用不会阻塞主线程(UI 线程)的异步方法发送

string reply = client.UploadStringAsync("http://192.168.3.230/index.htm", data);

如果您想使用 HttpWebRequest 类,请告诉我,我将编辑我的答案;)

于 2013-06-04T15:46:38.573 回答