通过winform发送邮件数据
本文关键字:数据 winform 通过 | 更新日期: 2023-09-27 18:16:57
我有一个通过以太网连接在静态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();
}
任何有关发送帖子的正确方法以及如何格式化帖子数据的帮助将是非常感激的。
您需要将数据发布到'setcmd '。不要把它添加到你发布的数据中。
// 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.
}
您应该在Fiddler之类的调试器中观察请求,并比较实际站点和您的代码发送的请求。在上面的代码片段中,一个可疑的事情是你以JSON格式发送数据,但声称它是"application/x-www-form-urlencoded"而不是"application/JSON"。
您可能还需要设置报头,如User-Agent,和/或cookie或身份验证报头。
如果你不需要多线程,web客户端可以完成这项工作。
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类让我知道,我会编辑我的答案;)