我想从本地服务器下载字符串。准确地说来自ESP8266的wifi模块。我在那里发布一个纯粹的字符串,如“TEST”。 我正在尝试
using (WebClient client = new WebClient())
{
string s = client.DownloadString("http://192.168.0.13");
MessageBox.Show(s);
}
但Exception抛出:
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>";
但错误是一样的。
对不起,我是这个新手......
答案 0 :(得分:1)
这不是最安全或更明智的解决方案,但是如果你想摆脱困境,你可以将它添加到你的.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。
答案 1 :(得分:0)
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";
}
}
}
&#13;
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";
}
}
}
&#13;