如何从服务器下载数据(ESP8266 WiFi模块)
本文关键字:ESP8266 WiFi 模块 数据 服务器 下载 | 更新日期: 2023-09-27 18:29:19
我想从本地服务器下载字符串。确切地说,来自ESP8266无线网络模块。我在那里发布了一个纯字符串,比如"TEST"。我正在试用
using (WebClient client = new WebClient())
{
string s = client.DownloadString("http://192.168.0.13");
MessageBox.Show(s);
}
但是异常抛出:
System.Net.WebException: The server committed a protocol violation. section=ResponseStatusLine
w System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request)
w System.Net.WebClient.DownloadString(Uri address)
w System.Net.WebClient.DownloadString(String address)
w logi.Logowanie.readEsp_Click(Object sender, EventArgs e) w d:'Projects Visual Studio'Projects'logi'logi'Logowanie.cs:line 81
我也尝试过在html中构建字符串,所以它看起来像:
string pagestr="<html><head><title>TEST</title></head><body<h2>Testing</h2></body></html>";
但是误差是相同的。
对不起,我是个新手。。。
这不是最安全或更明智的解决方案,但如果你想摆脱困境,你可以将其添加到你的.config
文件(在你的.NET项目上)中,以避免现在的问题:
<system.net>
<settings>
<httpWebRequest useUnsafeHeaderParsing="true" />
</settings>
</system.net>
但是您应该意识到您的WebServer代码存在一些问题。也许发布服务器代码可以让我们帮助您解决问题。
你也可以尝试这样做:
HttpWebRequest myHttpWebRequest1 =
(HttpWebRequest)WebRequest.Create("http://192.168.0.13");
myHttpWebRequest1.KeepAlive=false;
HttpWebResponse myHttpWebResponse1 =
(HttpWebResponse)myHttpWebRequest1.GetResponse();
通过这种方式,您可以将KeepAlive属性设置为false。
using System.IO;
using System.Net;
using System.Net.Http;
namespace WindowsFormsApplication8
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//setLabel();
Timer timer = new Timer();
timer.Interval = (100); // 10 secs
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
private void timer_Tick(object sender, EventArgs e)
{
setLabel();
}
public void setLabel()
{
var url = "http://192.168.0.105/data.txt";
var textFromFile = (new WebClient()).DownloadString(url);
label1.Text = textFromFile + "Kg";
}
}
}
using System.IO;
using System.Net;
using System.Net.Http;
namespace WindowsFormsApplication8
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//setLabel();
Timer timer = new Timer();
timer.Interval = (100); // 10 secs
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
private void timer_Tick(object sender, EventArgs e)
{
setLabel();
}
public void setLabel()
{
var url = "http://192.168.0.105/data.txt";
var textFromFile = (new WebClient()).DownloadString(url);
label1.Text = textFromFile + "Kg";
}
}
}
在esp8266代码上,在发送的响应之前添加此行
response = "HTTP/1.0 200 OK'r'nContent-type: text/html'r'n'r'n"
response += "any text or html code"
conn.send(response)
conn.close()