我正试图从压缩机接收数据,但它的响应始终为空。以下是我的代码:
WebClient client = new WebClient();
client.Headers[HttpRequestHeader.ContentType]= "application/x-www-form-urlencoded";
string question = "online_pressure";
string URL = "http://10.0.163.51/getVar.cgi";
string answer = client.UploadString(URL, "POST", question);
Console.WriteLine(answer);
当我将此代码用于另一个压缩器时,只有2个字符串与原先不同,它可以正常工作,并且我能在控制台中看到答案:
string question = "QUESTION=300201";
string URL = "http://10.0.163.50/cgi-bin/mkv.cgi";
VBS代码对于两个压缩机都能很好地运行。我可以从第一个和第二个压缩机的MsgBox中看到结果:
Dim objHTTP
strToSend = "online_pressure"
Set objHTTP = CreateObject("Microsoft.XMLHTTP")
Call objHTTP.Open("POST", "http://10.0.163.51/getVar.cgi", false)
objHTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
objHTTP.Send strToSend
MsgBox(objHTTP.ResponseText)
HttpRequest代码也适用于第二个压缩机:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
requestWriter.Write(data);
requestWriter.Close();
try
{
// get the response
WebResponse webResponse = request.GetResponse();
Stream webStream = webResponse.GetResponseStream();
StreamReader responseReader = new StreamReader(webStream);
string response = responseReader.ReadToEnd();
responseReader.Close();
Console.WriteLine(response);
}
catch (WebException we)
{
string webExceptionMessage = we.Message;
}
我应该尝试哪些方法来获取C#中第一个压缩机的数据?
[HttpWebRequest].ServicePoint.Expect100Continue = false;
设置到当前请求的ServicePoint而不是ServicePointManager的通用设置中。添加一个User-Agent
头和[HttpWebRequest].Headers.Add(HttpRequestHeader.CacheControl, "no-cache");
。如果失败,查看HttpStatusCode。 - Jimi