我正在尝试使用以下代码将命令发送到LAN上的Arduino以太网微控制器:
Dim request As HttpWebRequest = HttpWebRequest.Create("http://192.178.47.19:19/?r=")
Dim POST As String = "r1"
request.Method = "POST"
request.ContentType = "text/html"
request.Headers.Add("Access-Control-Allow-Origin: *")
request.ContentLength = POST.Length
request.KeepAlive = True
Dim requestStream As Stream = request.GetRequestStream()
Dim postBytes As Byte() = Encoding.ASCII.GetBytes(POST)
requestStream.Write(postBytes, 0, postBytes.Length)
requestStream.Close()
但是,我收到了错误:
Dim requestStream As Stream = request.GetRequestStream()
这样说:
底层连接已关闭:连接意外关闭。
仅使用jQuery和AJAX:
jQuery.support.cors = true;
$.ajax({
crossDomain: true,
async : true,
type: "POST",
headers: {'Access-Control-Allow-Origin': '*'},
url: "http://192.178.47.19:19/?r=" + whatsBeingSent,
data: '{}',
contentType: "text/html",
dataType: "html",
success: OnSuccessCallArduino,
error: OnErrorCallArduino
});
使用上面的代码工作得很好(当然在浏览器中)
那么为了让它在VB.net中运行,我会缺少什么?
答案 0 :(得分:0)
我有类似的问题。我在浏览器客户端中使用jQuery AJAX调用来访问运行生成WebRequest响应的函数的aspx文件。这通常没有问题。但是,如果函数使用WebRequest访问其他服务器,则响应很好,但永远不会返回到原始的AJAX调用并且应用程序挂起。
浏览器AJAX:
$.ajax({ dataType: "text", type: "POST", url: "WSProfile.aspx", async: false, data: { oper: 'FunctionSpecification', Data1: d1, Data2: d2 }, success: function (msg) { alert(msg); } });
WSProfile.Aspx:
Dim d1 As Text = Request.Form("Data1")
Dim d2 As Text = Request.Form("Data2")
Function getResponse(d1, d2)
Dim request As WebRequest = WebRequest.Create("http://urlname.com")
request.Method = "POST"
Dim postData As String = "data1=" & d1 & "&data2=" & d2
Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes(postData)
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = byteArray.Length
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As WebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
Dim Status As String = CType(response, HttpWebResponse).StatusDescription
dataStream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Response.Write(reader.ReadToEnd())
Response.Flush()
对其他URL的调用会返回响应,但对.aspx
文件的原始调用的Response.Write永远不会将数据返回给jQuery AJAX调用。